hibernate框架简单步骤

Demo.java

package com.itheima.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.itheima.domain.Customer;

/**
 * 测试Hibernate框架
 * @author Administrator
 *
 */
public class Demo {
    /**
     * 测试保存客户
     */
    @Test
    public void testSave(){
        //1、加载配置文件
        //2、创建SessionFactory对象,生成Session对象,不是以前学的那个Session,是框架产生的
        //3、创建session对象
        //4、开启事物
        //5、编写保存的代码
        //6、提交事务
        //7、释放资源
        /**
         * 代码都是固定的,只有第五步保存代码是不固定的
         */
        
        
        //1、加载配置文件
        Configuration config = new Configuration();
        //默认加载src目录下hibernate.cfg.xml的配置文件
        config.configure();
        
        //2、创建SessionFactory对象
        SessionFactory factory = config.buildSessionFactory();
        
        //3、创建session对象
        Session session = factory.openSession();
        
        //4、开启事物
        Transaction tr = session.beginTransaction();
        
        //5、编写保存的代码
        Customer c = new Customer();
        c.setCust_name("测试");
        c.setCust_level("2");
        c.setCust_phone("110");
        
        //■■保存数据,操作对象就相当于操作数据库,这是代码的核心■■
        session.save(c);
        
        //6、提交事务
        tr.commit();
        
        //7、释放资源
        session.close();
        factory.close();
        
    }
}

这是SessionFactory的配置文件:

package com.itheima.Utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate框架的工具类
 * @author Administrator
 *
 */
public class HibernateUtils {
    private static final Configuration CONFIG;
    private static final SessionFactory FACTORY;
    
    //编写静态代码块,在类在加载的时候,他就被执行了
    static{
        //加载XML的配置文件
        CONFIG = new Configuration().configure();
        //构建工厂
        FACTORY = CONFIG.buildSessionFactory();
        
    }
    
    /**
     * 从工厂中回去Session对象
     * @return
     */
    public static Session getSession(){
        return FACTORY.openSession();
    }
}

有了配置文件,Demo就简单了很多,我们可以对比一下:

package com.itheima.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.itheima.Utils.HibernateUtils;
import com.itheima.domain.Customer;

/**
 * 测试Hibernate框架
 * @author Administrator
 *
 */
public class Demo {
    /**
     * 测试保存客户
     */
    @Test
    public void testSave(){
        //配置文件可以做的事情:加载配置文件,获取Factory对象,获取session
        Session session = HibernateUtils.getSession();
        Transaction tr = session.beginTransaction();
        Customer c = new Customer();
        c.setCust_name("苍井空");
        session.save(c);
        //提交事务
        tr.commit();
        //释放资源
        session.close();
    }
}

 

posted @ 2017-04-10 07:15  tidhy  阅读(159)  评论(0编辑  收藏  举报