What does Hibernate.initialize do?

2019-02-12 04:03发布

What does Hibernate.initialize do?
Usually referred documentation talk only about

Hibernate.initialize(entity.lazyCollection)

Is there any sense in

Hibernate.initialize(entity)

4条回答
Lonely孤独者°
2楼-- · 2019-02-12 04:42

Hibernate in some cases returns proxy object like lazy collection or Session.load() etc. So if you have proxy object and want the real one you can manually initialize it.

查看更多
Melony?
3楼-- · 2019-02-12 04:49

I would say yes if the Entity has a lazily initialized field e.g. some large BLOB or CLOB data or a lazy one-to-one association. See 20.1.8. in the documentation for the former and 20.1.3 for the latter.

See also:

20.1.4. Initializing collections and proxies

查看更多
甜甜的少女心
4楼-- · 2019-02-12 04:57

Shortly Hibernate.initialize() creates another query to fetch object in persistence context. When object is loaded eagerly JPA makes only one query to fetch object. So another difference is number calls to server

In addition : 1. If object is null Hibernate.initialize() throws exception 2. Good source for how to initialize lazy associations http://www.thoughts-on-java.org/5-ways-to-initialize-lazy-relations-and-when-to-use-them/

查看更多
对你真心纯属浪费
5楼-- · 2019-02-12 04:59

I agree with Alan Hay, here is my experience, I've had this problem when running the JUNit tests, some of the lazy objects were not loading when trying to load the objects in another session. I had to call the Hibernate.initialize(Object) to load the lazy objects into the memory.

查看更多
登录 后发表回答