Delayed loading (no session or session was closed) means that the data is not loaded when it is read, but is loaded when it is used.
So how does hibernate know when data is used by users? How does one load data?
In fact, it is very simple. It uses a proxy mechanism. What is returned to the user is not the entity itself, but the proxy of the object. The proxy object loads data from the database when the user calls the getter method.
However, the database connection is required to load data. When we close the session, the database connection is closed at the same time. This is called the uninitialized relationship.
The conflict between delayed loading and session shutdown is generally handled as follows:
1. Use urgent loading:
Fetchtype. Eager: when an object is loaded, the attributes that are urgently loaded are immediately loaded from the database.
2. Obtain the data to be queried before closing the session (hibernate. initialize () method ).
3. Use interceptor or filter to control the session.
For example:
- <! -- Implement opensessioninview of spring -->
- <Filter>
- <Filter-Name> opensessioninviewfilter </filter-Name>
- <Filter-class> org. springframework. Orm. hibernate3.support. opensessioninviewfilter
- </Filter-class>
- <! -- The default value of singlesession is true. If it is set to false, opensessioninview is useless. Therefore, it can be left empty by default -->
- <Init-param>
- <Param-Name> singlesession </param-Name>
- <Param-value> true </param-value>
- </Init-param>
- <! --
- Specify the name of org. springframework. Orm. hibernate3.localsessionfactorybean in the spring configuration file. The default value is sessionfactory. If the name of localsessionfactorybean in spring is not sessionfactory, you must specify this parameter. Otherwise, the exception of sessionfactory cannot be found. Therefore, it can be left empty by default.
- -->
- <Init-param>
- <Param-Name> sessionfactorybean </param-Name>
- <Param-value> sessionfactory </param-value>
- </Init-param>
- </Filter>
- <Filter-mapping>
- <Filter-Name> opensessioninviewfilter </filter-Name>
- <URL-pattern>/* </url-pattern>
- </Filter-mapping>
Conflicts between delayed loading and session Shutdown