休眠:session.load 与 session.get

Hibernate: session.load vs session.get

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

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

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

UserDetails 的结构是

在评论区,一个人评论道:

there is no proxy of User class, instead the proxy object of the collection 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).

谢谢

这里,UserDetails是parent,Address是child。 Hibernate实际上是lazy-loadingchildAddress。因此,最终所有 children 元素(在本例中为 Address)在加载 parent(在本例中为 UserDetails)时都不是 pre-loaded。

所以,当您这样做时:

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

Hibernate 实际上并没有加载所有 child (Collection<Address>)。相反,只有当您显式访问它们时,Hibernate 才会加载 Address。所以 Hibernate 不会为 Address table 访问数据库,除非你真的需要它们,这就是 延迟加载 .

的目的

延迟加载 的意思是,当您获得 UserDetails 的代理 object 时,它并没有真正命中 Address table 除非您尝试显式访问 Collection 元素。换句话说,您需要遍历 Hibernate 的集合以获取 Address table.

您最终可能会陷入这样的境地:每次 child (Address) 时您都会访问数据库。因此,显式调用 listOfAddresses.size() 以便一次加载所有 children。

另请注意,对于 One-To-Many[=49=,默认情况下会发生 延迟加载 ] 例。

1.Fetching 策略: 获取策略在 session.get 或 session.load 的工作中没有效果(https://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch20.html#performance-fetching-lazy ).

2。 Session.get: 从不 return 代理 , 根据休眠文档:(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 方法首先检查缓存是否存在 fully initialize object 如果存在 return 则该对象否则它 hits the database to get the object 和 returns将其保存在缓存中后相同 space。

3。 Session.load: 根据休眠文档:

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 如果是 return 那个对象,否则它 return 是代理(代理是一个 class 委托给另一个对象。最初,当它没有初始化时,它只包含主键。当你调用一个方法时,正如 Javadoc 所说,它通过从数据库加载实际实体来初始化,以及该对象的此加载实体的委托)“假设该实例存在”。

注意: 重要的是要注意 load 方法 never throw an exception。如果您尝试检索任何其他 属性 而不是来自代理的主键 object.As 它将访问数据库以从那里加载对象,该对象不存在。