hibernate lazy loading of the principle of
When using the load method of query session records in the database, we return a proxy object, rather than the needs of that object; for example, there is a Student table in the database, we have cn.binyulan.doman.Student areas object, if the query Id value of "200,626,313" and Student stu = (Student) session.load (Student.class, "200626313"), and then we print System.out.println (stu.getClass); get the results cn. binyulan.domain.Student $ $ EnhancerByCGLIB $ $ 5a7cc325, very strange name it, this object is generated by Hibernate to help us, from the name you can see that it is the Student class to enhance the class object, in fact, this is a proxy object, this the object where the Student does not need the data, so if you shut down the session using the stu to obtain information, such as stu.getName (); will appear the following exception: org.hibernate.LazyInitializationException: could not initialize proxy - no Session, which illustrates the stu not we need the data.
stu object is now in the end what is it, it is actually a proxy class that has the ability to query the database when the session does not shut down when the call if we stu.getName () method; then the class would go to query the database and returns the corresponding data. Then we close the session after the Zaiqu use this class there will be no exception now, but if we call stu.getName () just to make the proxy class should go to the database, if people look at our code when two logically think this is a fundamental there would be no use, people can easily comment out a comment on the abnormal again, so hibernate provides a method Hibernate.initialize (stu); so that you can initialize the proxy object.
Do not know if It was noted that not, the above phrase code Student stu = (Student) session.load (Student.class, "200626313") to stu forced into a Student type, someone will ask: is the proxy object is not returned Mody, That how they cast it into the Student had, in fact, the proxy class is a subclass of Student, which has a greater capacity than the parent class (database queries), this class is how did it? In fact, hibernate using asm.jar and cglig-2.1.3.jar, modify the Student class in memory, the byte code, the modified byte-code class files that meet the rules, you can create a proxy object.
Domain objects should not be final, and we should now understand why the bar, if it is final, then not be able to inherit, of course, also can not create proxy object, also can not be achieved lazy loading, and if you do not lazy load , then the domain object design into fianl is also possible.