gpt4 book ai didi

java - hibernate session 的 get() 和 load() 方法在获取方面有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:08:34 24 4
gpt4 key购买 nike

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 :

  1. By default, hibernate creates run-time proxies. It loads the objects as a proxy unless a fetch mode is specified or set to false.

  2. That's because once the object is loaded in cache, the next subsequent calls perform repeatable read.

  3. Although the state of this object changes from persistent to detached

The entity can be retrieved in 2 ways.

load() - returns the proxy object with an identifier.

get() - returns the complete object from database.

for more details click this link

关于java - hibernate session 的 get() 和 load() 方法在获取方面有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22142920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com