Package Com;import Org.hibernate.session;import Org.hibernate.sessionfactory;import org.hibernate.Transaction; Import Org.hibernate.cfg.configuration;import org.junit.after;import Org.junit.before;import Org.junit.Test;import Com.entity.food;import Com.entity.husband;import Com.entity.user;import Com.entity.wife;import Com.entity.student.classes;import Com.entity.student.teacher;public class Test1 {private Session s;private Transaction Tran; @Beforepublic void before () {s=hibernateutils.getsession (); Tran=s.begintransaction ();} public void Test () {User user= (user) S.get (user.class,7);//Persistent too//user.setusername ("Xixixi");// Tran.commit () can also be saved without the use of the Save (), S.clear ();//Make the object not related to the session, out of the persistent too//to the Free State of the user into a persistent state tran=s.begintransaction (); S.update (user); User.setpassword ("789"); Tran.commit ();//Convert the object into shun-time too tran=s.begintransaction (); s.delete (user); Tran.commit ();} public void One2One () {Husband h=new Husband (); Wife w=new Wife ();//Create two instantaneous objects h.setname ("Xiaoming"); W.setname ("Baby"); W.sethusband (h); S.save (w); S.save (h);} @Testpublic void One2onequery () {Husband h= (Husband) S.get (Husband.class, 2); System.out.println (H.getname () + "-------------" +h.getwife (). GetName ());} @After public void After () {tran.commit (); Hibernateutils.closesession (s);}
Hibernate.cfg.xml
Package Com.entity;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.generationtype;import Javax.persistence.id;import javax.persistence.mappedsuperclass;@ Mappedsuperclasspublic class BaseEntity {@Id @generatedvalue (strategy=generationtype.auto) Private Integer Id;public Integer getId () {return ID;} public void SetId (Integer id) {this.id = id;}}
Baseentity.java
Package Com;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;public class Hibernateutils {private static sessionfactory sf;static{configuration Cfg=new configuration (). Configure ()//In the root directory src the path within the parentheses can omit the//configuration cfg=new Configuration (). Configure ("/ Hibernate.cfg.xml ");//read config file sf=cfg.buildsessionfactory ();} Construct session factory public static session getsession () {return sf.opensession ();} Get session public static void CloseSession (Session session) {if (session!=null) {session.close ();}} Close Session}
Hibernateutils.java
Used to read a configuration file, generate a session
Hibernate configuration file and an ID generate class Baseentity.java and a Hibernate tool class Hibernatutils.java