get() 和 load() 方法有什么区别?关于数据获取方法
public static void main(String[] args) {
SessionFactory factory= new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
tx = session.beginTransaction();
System.out.println("1 st time calling load method");
Account acc =
(Account)session.load(Account.class, 180);
System.out.println("bal"+acc.getBalance());
System.out.println("2nd time calling load method");
Account acc1=(Account)session.load(Account.class, 180);
System.out.println("bal"+acc1.getBalance());
System.out.println("1 st time calling get method");
Account acc2= (Account) session.get(Account.class, accId);
System.out.println("bal"+acc2.getBalance());
System.out.println("2 st time calling get method");
Account acc2= (Account) session.get(Account.class, accId);
System.out.println("bal"+acc2.getBalance());
tx.commit();
session.close();
}
我得到以下输出
1 st time calling load method
Hibernate:
/* load com.abcd.Account */ select
account0_.ACCOUNTID as ACCOUNTID1_0_,
account0_.ACCOUNTTYPE as ACCOUNTT2_1_0_,
account0_.CREATIONDATE as CREATION3_1_0_,
account0_.BALANCE as BALANCE1_0_
from
a.MYACCOUNT account0_
where
account0_.ACCOUNTID=?
bal3000.0
2nd time calling load method
bal3000.0
1 st time calling get method
bal3000.0
2 st time calling get method
bal3000.0
从输出中可以清楚地看出,get 方法没有命中数据库。它的行为类似于 load() 方法。谁能告诉我这种行为是否正确。
正如 T Mishra 所说here http://www.coderanch.com/t/606310/ORM/databases/Hibernate-load-confused-Hibernate-Proxies:
默认情况下,hibernate 创建运行时代理。除非指定获取模式或将其设置为 false,否则它将作为代理加载对象。
这是因为一旦对象加载到缓存中,接下来的后续调用就会执行可重复读取。
- 虽然这个对象的状态从持久化变成了分离
可以通过两种方式检索实体。
load() - 返回带有标识符的代理对象。
get() - 从数据库返回完整的对象。
欲了解更多详情,请点击这里link http://www.coderanch.com/t/606310/ORM/databases/Hibernate-load-confused-Hibernate-Proxies
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)