gpt4 book ai didi

java - Hibernate:session.load 与 session.get

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

我的印象是 session.load() 在缓存中加载代理对象,而 session.get() 总是访问数据库,但之后我很困惑观看 JavaBrains video .

根据这个视频,当我们调用下面的 get 方法时,它正在内存中加载 UserDetails 的代理对象。

user = (UserDetails) session.get(UserDetails.class, 1); 

UserDetails 的结构是

enter image description here

在评论区,有人评论道:

there is no proxy of User class, instead the proxy object of thecollection is created.

现在这里有两个问题。

1st: Related to fetching strategies and creation of proxy objects in case of session.load() and session.get() which has been answered below by me.

2nd: In this case, the proxy object will create for UserDetails or for collection (still to be answered).

谢谢

最佳答案

1.抓取策略:抓取策略对session.get或session.load(https://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch20.html#performance-fetching-lazy)的工​​作没有影响。

<强>2。 Session.get:它从不返回代理,根据 hibernate 文档:(https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#get(java.lang.Class,java.io.Serializable))

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.)

表示 get 方法首先检查缓存是否存在完全初始化对象 如果是则返回该对象否则它访问数据库以获取对象 并在将其保存在缓存空间后返回相同的内容。

<强>3。 Session.load: 根据 hibernate 文档:

Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.

意味着 load 方法首先检查缓存中是否存在 fully initialize object 如果是则返回该对象否则它返回代理(代理是一个类委托(delegate)给另一个对象。最初,当它没有初始化时,它只包含主键。当你调用一个方法时,正如 Javadoc 所说,它通过从数据库加载实际实体和委托(delegate)到这个加载的实体来初始化)通过“假设该实例存在”来确定该对象。

注意重要的是要注意load方法永远不会抛出异常。你会得到ObjectNotFoundException以防万一您尝试从代理对象中检索任何其他属性而不是主键。因为它将访问数据库以从那里加载对象,而该对象不存在。

关于java - Hibernate:session.load 与 session.get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46144731/

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