I. Status of Hibernate objects
The entity class object has 3 states in Hibernate: instantaneous, persistent, and off-tube.
Instantaneous: There is no relationship with Hibernate, there is no corresponding record in the database, and once the JVM is over, the object disappears.
Persistent: An object is associated with Hibernate, has a corresponding session, and has a corresponding record in the database
Off-tube: An object has a corresponding record in the database, but its corresponding session is closed.
First the new product () pair image, there is no corresponding record in the database, this time the Product object state is instantaneous
The object is stored in the database through the Save method of the session, and the object is associated with the session, where the state is persistent
Finally closed the session, the object in the database has the corresponding data, but has lost contact with the session, is to take off the tube.
Packagecom.demo.test;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.cfg.Configuration;Importcom.demo.pojo.Product; Public classtesthibernate{ Public Static voidMain (string[] args) {sessionfactory sf=NewConfiguration (). Configure (). Buildsessionfactory (); Session s=sf.opnesession (); Product P=NewProduct (); P.setname ("Demo");//Create an Entity object, and then assign a value, at which point it is just instantaneousSystem.out.println ("P is instantaneous state" at this time); S.save (p);//call the session's Save () methodSystem.out.println ("P is a persistent state at this time"); S.close ();//after closing the session connectionSystem.out.println ("P is off-state at this time"); Sf.close (); }}View Code
Second, Hibernate Insert Object
We can insert the object into the database through a for loop and insert the data using the Save () method of the session.
Importorg.hibernate.cfg.Configuration;Importcom.demo.pojo.Product; Public classtesthibernate{ Public Static voidMain (string[] args) {sessionfactory sf=NewConfiguration (). Configure (). Buildsessionfactory (); Session s=sf.opnesession (); S.begintransaction (); for(inti=0;i<10;i++) {Product P=NewProduct (); P.setname ("Demo" +i); P.setprice (i); S.save (P); } s.gettransaction (). Commint (); S.close (); Sf.close (); }View Code
Third, hibernate get the object
There are two ways to get objects by ID, get and load
Difference: 1, Delay loading 2, for the ID does not exist when the processing
Load
Ii. Persistent Layer Framework (Hibernate)