Hibernate can generally be done by session.load or session.get when querying the corresponding records from the database into a Java entity
(1) Load method
@Test publicvoid testLoad () { = sf.getcurrentsession (); Session1.begintransaction (); = (Student) session1.load (Student. Class, a); System.out.println (T.getage ()); Session1.gettransaction (). commit (); }
Hibernate load is normal when using return object before session closes
Hibernate:select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0 _ Where student0_.id=?
If the call is removed. As follows
@Test publicvoid testLoad () { = sf.getcurrentsession (); Session1.begintransaction (); = (Student) session1.load (Student. Class, a); // System.out.println (T.getage ()); session1.gettransaction (). commit (); }
Hibernate does not invoke a query statement when executing the above program.
If the call is placed after the session is closed, the following
@Test publicvoid testLoad () { = sf.getcurrentsession (); Session1.begintransaction (); = (Student) session1.load (Student. Class, a); Session1.gettransaction (). commit (); System.out.println (T.getage ()); }
The following exception appears
Org.hibernate.LazyInitializationException:could not initialize Proxy-no Session
At Org.hibernate.proxy.AbstractLazyInitializer.initialize (abstractlazyinitializer.java:165)
At Org.hibernate.proxy.AbstractLazyInitializer.getImplementation (abstractlazyinitializer.java:286)
At Org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke (javassistlazyinitializer.java:185)
.....
(2) Get method
@Test publicvoid testget () { = sf.getcurrentsession (); Session1.begintransaction (); = (Student) session1.get (Student. Class, a); Session1.gettransaction (). commit (); System.out.println (T.getage ()); }
After the Get method returns the corresponding object, whether it is called before the session closes or after it is closed, the query can be queried normally.
Hibernate:select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0 _ Where student0_.id=?
After the Get method returns the corresponding object, it can still query normally, even if the object is not called.
Comprehensive:
(1) The Load method of the session returns the object instead of executing the query from the database immediately, but instead uses the dynamic proxy, which is called lazy when the properties in the object are called Hibernate to execute the query.
If the session is closed at this point, a load exception occurs.
(2) The Get method of the session is to execute the corresponding query from the database as soon as the object is returned, encapsulating the return record into the corresponding entity
Hibernate learn the difference between load and get 5_session