Write the Hibernateutil class relative to the code in the Hibernate series (i) to increase the speed of the program
First, you still have to write a JavaBean (User.java):
Package Cn.itcast.hibernate.domain;import Java.util.date;public class User {private int id;private String name;private Date birthday;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Date Getbirthday () {return birthday;} public void Setbirthday (Date birthday) {this.birthday = birthday;}}
Then, add a mapping file under the current package: User.hbm.xml
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
After that, we will configure HIBERNATE.CFG.CML, which is placed directly below the SRC directory:
<?xml version= ' 1.0 ' encoding= ' utf-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">
Next, we're going to write the Hibernateutil.java class, which is basically to get the session.Because, every time we get a session in the code is very time consuming, we want it to do it only once, so we're going to do a tool class to initialize hibernate. And because the tool class generally does not want to be inherited, so that the user can change the tool class things, so generally we will use the final keyword.
Package Cn.itcast.hibernate;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;public Final class Hibernateutil {private static Sessionfactory sessionfactory;private Hibernateutil () {}static{configuration cfg = new Configuration (); Cfg.configure ( ); sessionfactory = Cfg.buildsessionfactory ();} public static Sessionfactory Getsessionfactory () {return sessionfactory;} public static Session GetSession () {return sessionfactory.opensession ();}}
We then write a simple test class that adds a data add.java:Package Cn.itcast.hibernate;import Java.util.date;import Org.hibernate.session;import org.hibernate.Transaction; Import Cn.itcast.hibernate.domain.user;public class Add {public static void main (string[] args) {Session s = hibernateutil . GetSession (); Here, the GetSession () method in the Hibernateutil tool class is called directly to get sessiontransaction tx = S.begintransaction (); Open Transaction User user = new user (); User.setname ("Zhangsan"); User.setbirthday (new Date ()); S.save (user); Save Object Tx.commit ();//COMMIT Transaction s.close ();//Close Session}}
Thus, a simple hibernateutil class that gets the session to improve the performance of the program is written.
Hibernate series (ii): Simply write the Hibernateutil class to optimize performance