1. First import the required jar packages
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/57/35/wKiom1SUILLCr-0NAADvmylrdcc243.jpg "title=" 1.png " alt= "Wkiom1suillcr-0naadvmylrdcc243.jpg"/>
2. Create the Hibernate.cfg.xml file in 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 ">3. Create domain:
Package Cn.itcast.hibernate0909.domain;import Java.io.serializable;public class person implements serializable{ Private long pid;private string pname;private string psex;public Long getpid () {return PID;} public void Setpid (Long pid) {this.pid = pid;} Public String Getpname () {return pname;} public void Setpname (String pname) {this.pname = pname;} Public String Getpsex () {return psex;} public void Setpsex (String psex) {this.psex = Psex;}}
4. Create the appropriate Person.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 ">5. Create a test class
Package Cn.itcast.hibernate0909.helloworld;import Org.hibernate.session;import org.hibernate.SessionFactory; Import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.junit.test;import Cn.itcast.hibernate0909.domain.person;public class Persontest {@Testpublic void Testsaveperson () {Configuration Configuration = new configuration ();//load Config file configuration.configure ();//create sessionfactorysessionfactory with Factory mode Sessionfactory = Configuration.buildsessionfactory (); Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Person man = new Person ();//Since the primary key is generated in the mapping file, it is not necessary to set the primary key Person.setpname ("team player") in the program;p Erson.setpsex ("pure Man"); Session.save (person); Transaction.commit (); Session.close ();}}
First Hibernate program