What is the advantage of load() vs get() in Hibernate?

  • Use get() when you want to load an object
  • Use load() when you need to obtain a reference to the object without issuing extra SQL queries, for example, to create a relationship with another object:

Ex: if you are trying to load /get Empoyee object where empid=20. But assume record is not available in DB.

 Employee employee1 = session.load(Employee.class,20);  //Step-1
 system.out.println(employee1.getEmployeeId();       //Step-2  --o/p=20
 system.out.println(employee1.getEmployeeName();       //Step-3 -->O/P:ObjectNotFoundException

If you use load in step-1 hibernate wont fire any select query to fetch employee record from DB at this moment.At this pint hibernate gives a dummy object ( Proxy ). This dummy object doesnt contain anything. it is new Employee(20). you can verify this in step-2 it will print 20. but in step-3 we are trying to find employee information. so at this time hibernate fires a sql query to fetch Empoyee objct. If it is not found in DB.throws ObjectNotFoundException.

Employee employee2 = session.get(Employee.class,20);  //Step-4

for session.get() hibernate fires a sql query to fetch the data from db. so in our case id=20 not exists in DB. so it will return null.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值