Hiernate里get和load的区别

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.两者采取不同的延迟检索策略;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值