hibernate lazy

sponsored links
Could not initialize proxy - the owning Session was closed
Hibernate session is closed because, as a result of lazy = true, action call session.load () has been the target is free and can not be changed, the method should be placed in the dao

Hibernate issues on the lazy Detailed (Classic)
Could not initialize proxy - the owning Session was closed (the length of a)

2007-05-11 09:52

In fact, writing this very very clear that the conversation closed, unable to operate Hibernate entities. This situation caused a lot of mistakes, what to write, ah, ah logical error.

But this says about the lazy mechanism:

Delay the use of Hibernate initialization errors are the most common development mistakes. If a class or configuration of the delay in collection of search strategy, it must be when the proxy class instance or a collection agent in a persistent state (that is, in the Session scope) in order to initialize it. If the free state when it is initialized, it will have a delayed initialization error.

The following documents to Customer.hbm.xml elements <class> attribute lazy is set to true, that the use of delayed retrieval strategies:

<class name="mypack.Customer" table="CUSTOMERS" lazy="true">

When the Executive Session of the load () method, Hibernate will not execute the query immediately CUSTOMERS table select statement, only to return to the proxy class Class Customer example, the proxy class with the following features:

(1) from Hibernate dynamically generated at run time, it extends the Customer class, so it inherits all the attributes of type Customer and methods, but it is the realization of the application is transparent.
(2) When the Hibernate proxy class to create Customer instances, the only initialization of the OID of its attributes, other attributes are null, so this type of instance agents occupy very little memory.
(3) When the application first visit Customer proxy class instances (for example, call customer.getXXX () or customer.setXXX () method), Hibernate will initialize the proxy class instance, the initialization process of the implementation of select statements, truly Customer from the database to load all the data objects. However, an exception, and that is when the application instance of a class visit to the Customer Agent getId () method, Hibernate will not initialize proxy class instances, as in the creation of categories instance OID agent there, and do not have to query the database .

Tip: Hibernate tools used to generate CGLIB classes of durable type of agent. CGLIB is a powerful tool to generate Java byte code, it can run in the extension of dynamically generated when the Java class or Java interface to achieve the proxy class. More knowledge on the CGLIB, please refer to: http://cglib.sourceforge.net/.

Session adopted the following code before the load () method to load Customer object, and then visit its name attribute:

tx = session.beginTransaction ();
Customer customer = (Customer) session.load (Customer.class, new Long (1));
customer.getName ();
tx.commit ();

Running session.load () method Hibernate does not execute any select statement, only to return to the proxy class Class Customer examples, and its OID is 1, this is determined by load () method's second parameter specified. When the application calls customer.getName () method, Hibernate will initialize the proxy class instance of Customer, Customer from the database object to load data, perform the following select statement:

select * from CUSTOMERS where
select * from ORDERS where CUSTOMER_ID = 1;

When the lazy attribute <class> elements for true, would affect the Session of the load () method of the various run-time behavior, the following example.

1. If the Customer object is loaded in the database does not exist, Session of the load () method will not be thrown only when running customer.getName () method will be dished out the following anomalies:

ERROR LazyInitializer: 63 - Exception initializing proxy
net.sf.hibernate.ObjectNotFoundException: No row with the given identifier exists: 1, of class:
mypack.Customer

2. If in the Session scope, the application has not visited the Customer object, then the Customer has been an example of proxy class will not be initialized, Hibernate will not execute any select statement. The following code attempts to close the Session object free to visit Customer:

tx = session.beginTransaction ();
Customer customer = (Customer) session.load (Customer.class, new Long (1));
tx.commit ();
session.close ();
customer.getName ();

Variable as a result of customer references quoted Acting Class Customer examples in the Session scope has never been initialized, so in the implementation of customer.getName () method, Hibernate will be dished out the following anomalies:

ERROR LazyInitializer: 63 - Exception initializing proxy
net.sf.hibernate.HibernateException: Couldnotinitializeproxy-theowningSessionwasclosed

It can be seen, Customer Agent class examples only in the framework of the current Session to be initialized.

3. net.sf.hibernate.Hibernate kind of initialize () static method in the Session scope for explicit examples of proxy class initialization, isInitialized () method has been applied to determine whether the proxy class instance has been initialized. For example:

tx = session.beginTransaction ();
Customer customer = (Customer) session.load (Customer.class, new Long (1));
if (! Hibernate.isInitialized (customer))
Hibernate.initialize (customer);
tx.commit ();
session.close ();
customer.getName ();

The code above in the Session through the Hibernate type of the scope of the initialize () method to initialize the Customer explicit examples of proxy class, so after the closure of Session, you can visit the Customer free of normal objects.

4. When the proxy type application instance getId () method, will not trigger initialization Hibernate proxy class instances, such as:

tx = session.beginTransaction ();
Customer customer = (Customer) session.load (Customer.class, new Long (1));
customer.getId ();
tx.commit ();
session.close ();
customer.getName ();

When applications access customer.getId () method, the method of direct return to Customer Agent OID value type instance, the need to query the database. Variable as a result of customer references always cited is the Customer has not been initialized instance of proxy class, so after the Executive Session closed customer.getName () method, Hibernate will be dished out the following anomalies:

ERROR LazyInitializer: 63 - Exception initializing proxy
net.sf.hibernate.HibernateException: Couldnotinitializeproxy-theowningSessionwasclosed

Solution:

Due to hibernate using lazy = true, so that when you use hibernate query, the actual return for the use of enhanced cglib proxy class, but its not practical to fill; when you are front-end, using it to value (getXXX), the time Hibernate will execute the query to the database, and fill, but at this time if the type associated with this agent have been closed out of the session, it will have a different error.
When doing one-to-many, sometimes "could not initialize proxy - clothe owning Session was sed, this seems to be the problem hibernate cache. Problem-solving: the need for <many-to-one> Lane lazy =" false ". However, abnormal may trigger another call

failed to lazily initialize a collection of role: XXXXXXXX, no session or session was closed

This unusual solution, please see my blog (http://hi.baidu.com/kekemao1) of the Hibernate abnormal "failed to lazily initialize a collection of role anomaly"

?
Solution: add in the web.xml
<filter>
<filter-name> hibernateFilter </ filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</ filter-class>
</ filter
<filter-mapping>
<filter-name> hibernateFilter </ filter-name>
<url-pattern> *. do </ url-pattern>
</ filter-mapping>
You can;

Reference to:
Hibernate with lazy loading:

Hibernate object-relational mapping provided by the delay and non-delayed initialization of the object. Non-lazy loading in the time to read an object with this object will all read it together with other objects. This may sometimes lead to hundreds of (if not thousands of words) select statement when reading the implementation object. Sometimes this problem appears in the use of two-way relationship often lead to the entire database in the initialization phase has been read out. Of course, you could have taken the trouble to check each object and other object relations, and to delete those who are most expensive, but in the end, we may lose the ORM tool like the convenience of access.

One obvious solution is to use Hibernate's lazy loading mechanism provided. Initialization strategy that targets only one call it when one-to-many or many-to-many relationship between the object will be read out of the relationship. This process is transparent to developers, and only very few requests for database operations, it will be more obvious performance. One disadvantage of this technology is the delay in loading the technical requirements of a Hibernate Session object to the use of time has been open. This will become a model through the use of DAO abstract persistence layer out of a major problem. Persistence mechanisms in order to completely abstract out the logic of all the databases, including open or closed session, we can not appear in the application layer. The most common is the fact that some interface to achieve a simple DAO implementation class to database logic package up. A fast but clumsy solution is to abandon the DAO mode, will be added to the database connection logic to the application layer. This may be of some small and effective application, but in large systems, this is a serious design flaw, the system can hinder scalability.

Delays in loading Web layer

Fortunately, Spring framework Hibernate lazy loading with DAO integration model provides a convenient solution. For those not familiar with the use of Spring integration with Hibernate, I will not discuss too many details here, but I suggest you to learn about Spring integration with Hibernate data access. A Web application as an example, Spring provides a OpenSessionInViewFilter and OpenSessionInViewInterceptor. We can choose a category to achieve the same functionality. The only difference the two methods on the interceptor in the Spring container is running and configured in the context of web applications, and Filter before running in the Spring and in the configuration in web.xml. No matter what, they will request the current session with the current (database) when the thread open Hibernate Session bound. Once the threads have been bound to, this has opened up in the Hibernate session in DAO implementation class to use transparent. This session will load the database for the delay in view of the value of the object to keep it open. Once completed this logical view, Hibernate session in Filter's doFilter method of the Interceptor or be closed postHandle methods. The following is a sample configuration of each component:

Interceptor configuration:

<beans>
<bean
class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="openSessionInViewInterceptor"/>
</ list>
</ property>
<property name="mappings">

</ bean>

<bean name = "openSessionInViewInterceptor"
class = "org.springframework.orm.hibernate.support.OpenSessionInViewInterceptor">
<property name="sessionFactory"> <ref bean="sessionFactory"/> </ property>
</ bean>
</ beans>

Filter configuration

<web-app>

<filter>
<filter-name> hibernateFilter </ filter-name>
<filter-class>
org.springframework.orm.hibernate.support.OpenSessionInViewFilter
</ filter-class>
</ filter>

<filter-mapping>
<filter-name> hibernateFilter </ filter-name>
<url-pattern> *. spring </ url-pattern>
</ filter-mapping>

</ web-app>

The realization of the Dao interface Hibernate to use to open the conversation is very easy. In fact, if you have used the Spring framework to achieve your Hibernate Dao, is very likely you do not need to change anything. HibernateTemplate convenient public access to the database into a component so that a piece of cake, but only through the DAO interface components can access to the database. The following is an example of the DAO:

public class HibernateProductDAO extends HibernateDaoSupport implements ProductDAO (

public Product getProduct (Integer productId) (
return (Product) getHibernateTemplate (). load (Product.class, productId);
)

public Integer saveProduct (Product product) (
return (Integer) getHibernateTemplate (). save (product);
)

public void updateProduct (Product product) (
getHibernateTemplate (). update (product);
)
)

Used in the Business Logic Tier Lazy Loading

Even in the view outside, Spring framework, through the use of AOP interceptors to make lazy loading HibernateInterceptor become very easy to implement. The Hibernate interceptor will be called transparent configuration in Spring application context of the business object method to intercept the request down, prior to the call to open a Hibernate session, and then after the implementation of the method, then the closure will be. Let us look at a simple example, suppose we have an interface BussinessObject:

public interface BusinessObject (
public void doSomethingThatInvolvesDaos ();
)
BusinessObject category achieved BusinessObjectImpl interface:

public class BusinessObjectImpl implements BusinessObject (
public void doSomethingThatInvolvesDaos () (
/ / Lots of logic that calls
/ / DAO classes Which access
/ / Data objects lazily
)
)

Spring applications in the context of a number of configurations, we are able to approach the call intercept BusinessObject down, and then make its way to support lazy loading. A program to see if the following fragment:

<beans>
<bean>
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</ property>
</ bean>
<bean>
<property name="someDAO"> <ref bean="someDAO"/> </ property>
</ bean>
<bean>
<property name="target"> <ref bean="businessObjectTarget"/> </ property>
<property name="proxyInterfaces">
<value> com.acompany.BusinessObject </ value>
</ property>
<property name="interceptorNames">
<list>
<value> hibernateInterceptor </ value>
</ list>
</ property>
</ bean>
</ beans>

BusinessObject when the time is called, HibernateInterceptor open a Hibernate session, and call the request object passed to the BusinessObjectImpl. When after the completion of BusinessObjectImpl implementation, HibernateInterceptor transparent closed the conversation. Application layer of code do not understand the logic of any persistence layer, or the realization of a deferred load.

Unit testing in test lazy loading

Finally, we need to test the J-Unit delay our loader. We can easily rewrite the TestCase class setUp and tearDown methods to achieve this requirement. I prefer to use this abstract class as a convenient all my test base class type.

public abstract class MyLazyTestCase extends TestCase (

private SessionFactory sessionFactory;
private Session session;

public void setUp () throws Exception (
super.setUp ();
SessionFactory sessionFactory = (SessionFactory) getBean ( "sessionFactory");
session = SessionFactoryUtils.getSession (sessionFactory, true);
Session s = sessionFactory.openSession ();
TransactionSynchronizationManager.bindResource (sessionFactory, new SessionHolder (s));

)

protected Object getBean (String beanName) (
/ / Code to get objects from Spring application context
)

public void tearDown () throws Exception (
super.tearDown ();
SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource (sessionFactory);
Session s = holder.getSession ();
s.flush ();
TransactionSynchronizationManager.unbindResource (sessionFactory);
SessionFactoryUtils.closeSessionIfNecessary (s, sessionFactory);
)
)
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of hibernate lazy

  • Struts Spring Hibernate test Noodles

    Hibernate working principle and why to use? Principle: 1. To read and parse configuration file 2. Read and analytic mapping information, create a SessionFactory 3. Open Sesssion 4. Create Affairs transation 5. Persistence operation 6. Submitted Services 7

  • spring hibernate Services

    2008-09-28 09:57 <! - The definition of Transaction Manager (Declarative Services) -> <bean > <property name="sessionFactory"> <ref local="sessionFactory" /> </ property> </ bean> <! - Busine ...

  • js examples of common events

    <html> <head> <script type="text/javascript"> / / Which mouse button is clicked function whichButton1 (event) ( if (event.button == 2) ( alert ( "You clicked the right mouse button!") ) else ( alert ( "You c ...

  • SUI-JavaScript rich UI library integration solution

    Introduction: SUI is not a class implementation of the UI, nor is it a standard set of UI markup language, it is just to help the existing UI frameworks (such as Ext, YUI like) to mark the way to the statement and the creation of UI. The names of these ta

  • [Have resolved] how to give rails of the model class of congestive (include / extent module)

    Has been resolved Please visit: http://henrik.nyh.se/2008/02/rails-model-extensions 1: the introduction of new features to the controller My approach: I tried to introduce in the application controller extra modules: require "string" This "string

  • Properties with 6 supplementary hibernate.cfg.xml configuration

    In some special circumstances, we may be saved in the database connection information config.properties document, for example, make a install.jsp to modify config.properties documents, implementation of online information on the database configuration. At

  • Real design pattern

    I hate the thought of the time to teach some provide a lot of code, because I think the thought process of acceptance should be a pleasure to read as a novel process, rather than spend a lot of brain power for a certain process details And this world ...

  • JAVA Class naming convention

    1. Entity Layer: Inheritance: All categories inherited from BasicEntity, one of BasicEntity implementation java.io.Serializable interface; Naming rules: Class Name = Object + type suffix, one of type suffix for Bean, such as: SalesOrderBean 2. Form l ...

  • Application of spring struts2.0 hibernate HQL

    Therefore, in the development of statistical inquiry system, as far as possible through the use of select statement to write the required query property way back relational data, and avoid using the first query return persistent object (in this way are in

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries