一、session和get()方法和load()方法的区别
执行get方法的时候会去执行sql语句去数据中查询记录并返回对,如果查不到数据则返回null。
而load方法则不会真的去发出sql语句,返回一个实体代理对象(当前这个对象可以自动转化为实体对象),但当代理对象被调用时,才会去发出sql语句去数据库中并返回对象。也就是我们所说的懒加载。如果没有数据不存在,就会抛出个org.hibernate.ObjectNotFoundException异常。
load先到缓存(session缓存/二级缓存)中去查,如果没有则返回一个代理对象(不马上到DB中去找),等后面使用这个代理对象操作的时候,才到DB中查询,这就是我们常说的 load在默认情况下支持延迟加载(lazy)
注意:无论是查询还是删更改,都要先开启事务
@Test
public void testGet() {
Session session1 = sessionFactory.getCurrentSession();
session1.getTransaction().begin();
Teacher t = (Teacher)session1.get(Teacher.class, 1);
session1.getTransaction().commit();
}
结果:
21:21:14,927 WARN DriverManagerConnectionProviderImpl:93 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
Hibernate:
select
teacher0_.id as id1_3_0_,
teacher0_.birthday as birthday2_3_0_,
teacher0_.name as name3_3_0_,
teacher0_.rank as rank4_3_0_,
teacher0_.title as title5_3_0_
from
teacher teacher0_
where
teacher0_.id=?
Process finished with exit code 0
验证了执行get方法的时候执行sql语句
来看load方法的情况
@Test
public void testLoad() {
Session session1 = sessionFactory.getCurrentSession();
session1.getTransaction().begin();
Teacher t = (Teacher)session1.load(Teacher.class, 1);
session1.getTransaction().commit();
}
结果如下:
21:26:47,243 WARN DriverManagerConnectionProviderImpl:93 - HHH000402: Using Hibernate built-in connection pool (not for production use!)