1.
1.1 获取Session的两种方式
Session是Hibernate的核心,我们在创建了SessionFactory对象后,有两种方式可以获取Session实例
- Session session = sessionFactory.
openSession();
采用openSession方法获取Session实例时,SessionFactory直接创建一个新的Session实例,并且在使用完成后需要调用close方法进行手动关闭。 - Session session = sessionFactory.
getCurrentSession();
而getCurrentSession方法创建的Session实例会被绑定到当前线程中,它在提交或回滚操作时会自动关闭。
1.2 Session的事务管理—Transaction对象
我们通过Session开启事务,获取Transaction
对象
//开启事务
Transaction transaction = session.beginTransaction();
// 提交事务
transaction.commit();
// 回滚事务
transaction.rollback();
Session执行完数据库操作后,要使用Transaction接口的commit()方法进行事务提交,才能真正的将数据操作同步到数据库中。发生异常时,需要使用rollback()方法进行事务回滚,以避免数据发生错误。
由于Session对象属于线程不安全,当一个线程有多个Session时,无法保证事务。所以一个线程要保障只有一个Session对象。
为了保证一个线程中只有一个Session,所以在实际开发中,我们将Session绑定到当前线程中
1.3 get方法和load方法
Hibernate中get()和load()的区别
在hibernate.cfg.xml中开启显示SQL语句
<property name="hibernate.show_sql">true</property>
dao类
public class CustomerDao {
/**
* 根据id查询客户信息 get立即加载
*/
public static Customer findOneById(long id){
Session session = null;//Session对象
try{
// 查询不需要开启事务,只有对数据库内容进行多次增删改操作时
session = HibernateUtil.openSession();
Customer newCustomer = session.get(Customer.class, id);
return newCustomer;
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();//释放资源
}
return null;
}
/**
* 根据id查询客户信息 load延迟加载
*/
public static Customer loadOneById(long id){
Session session = null;//Session对象
try{
// 查询不需要开启事务,只有对数据库内容进行多次增删改操作时
session = HibernateUtil.openSession();
Customer newCustomer = session.load(Customer.class, id);
return newCustomer;
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();//释放资源
}
return null;
}
}
HibernateUtil
public class HibernateUtil {
private static SessionFactory factory;
// 使用静态代码块获取SessionFactory
static {
//细节:Hibernate把所有可预见的异常,都转成了运行时异常(工具中不会提示要添加异常块)
try {
// 加载hibernate.cfg.xml配置文件
Configuration config = new Configuration().configure();
factory = config.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取一个新的Session对象(每次都是一个新对象)
* @return
*/
public static Session openSession(){
return factory.openSession();
}
/**
* 获取一个新的Session对象(每次都是一个新对象)
* @return
*/
public static Session getCurrentSession(){
return factory.getCurrentSession();
}
}
测试
@Test
public void testGet(){
Customer oneById = CustomerDao.findOneById(1L);
System.out.println("-------------------------");
System.out.println(oneById);
}
当get()方法被调用的时候就会立即发出SQL语句,使用get()和普通的单条查询并没有多大的区别。
2.Session、EntityManager、HibernateTemplate的区别
- Session是Hibernate操作数据库的对象
- EntityManager是JPA操作数据库的对象
- HibernateTemplate是Spring整合Hibernate后操作数据库的对象(底层是session)