Hiernate里get和load的区别:
实体类:
public class Book {//省略get和set方法
private Integer id;
private String name;
private String author;
private Double price;
}
测试类:
@Test
public void test01(){
// 1、创建一个SessionFactory对象
SessionFactory sessionFactory = null;
1.1创建Configuration对象
Configuration configure = new Configuration().configure();
// 创建一个ServiceRegistry对象
需要在该对象当中注册hibernate的任何配置和服务才能有效
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configure.getProperties()).buildServiceRegistry();
sessionFactory= configure.buildSessionFactory(serviceRegistry);
2、创建一个Session对象
Session session = sessionFactory.openSession();
3、开启事务
Transaction transaction = session.beginTransaction();
4、执行操作
Book bk1=(Book) session.get(Book.class, 7);
//数据库里没有7这条数据
System.out.println(bk1);
Book bk2=(Book)session.load(Book.class, 7);
System.out.println(bk2);
5、提交事务
transaction.commit();
6、关闭session
session.close();
7、关闭SessionFactory
sessionFactory.close();
}
运行结果:
bk1:
Hibernate:
select
book0_.id as id1_0_0_,
book0_.name as name2_0_0_,
book0_.author as author3_0_0_,
book0_.price as price4_0_0_
from
book book0_
where
book0_.id=?
null
bk2:
Hibernate:
select
book0_.id as id1_0_0_,
book0_.name as name2_0_0_,
book0_.author as author3_0_0_,
book0_.price as price4_0_0_
from
book book0_
where
book0_.id=?
没输出,并且junit报错
两者区别:
- 1.当数据不存在与OID对应的记录时,get返回null,而load则报错
- 2.两者采取不同的延迟检索策略;