An example of a configuration:
1. First create a table CAT in the database
Create Table Cat
CAT_ID VARCHAR (20) Primary Key Not Null,
Name varchar (20) Not null,
SEX Char (1))
2. Establish hibernate.cfg.xml and generate hibernaetfactory.class to manage him
Hibernate.cfg.xml
XML Version = '1.0' encoding = 'UTF-8'?>
"- // Hibernate / Hibernate Configuration DTD 2.0 // en"
"
http://hibernate.sourceForge.Net/Hibernate-configuration-2.0.dtd ">>
session-factory>
hibernate-configuration> hibernaetfactory.javaPackage com.mdcl.hibaNate;
Import net.sf.hibelnate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.cfg.configuration;
/ ** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html}. * / Public class HibernateFactory {
/ ** * Location of hibernate.cfg.xml file * NOTICE:.. Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file That * is place the config file in a Java package - the default location * is the default Java package
* Examples:..
* CONFIG_FILE_LOCATION = "/hibernate.conf.xml" * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml ". code> * / private static string config_file_location =" /Hibernate.cfg.xml";/** Holds a single instance of session * / private static final threadlocal threadlocal = new threadlocal ();
/ ** The Single Instance of Hibernate Configuration * / Private Static Final Configuration CFG = New Configuration ();
/ ** The single instance of hibernate SessionFactory * / private static net.sf.hibernate.SessionFactory sessionFactory; public static Session currentSession () throws HibernateException {Session session = (Session) threadLocal.get ();! If (session = null && ! session.isopen ()) session = null; if (session == null) {if (sessionFactory == null) {Try {cfg.configure; sessionFactory = cfg.buildsessionFactory ();} catch (Exception E) {System.err .println ("%%%% Error Creating HibernateSessionFactory %%%); E.PrintStackTrace ();}} session = sessionFactory.OpenSession (); threadlocal.set (session);} returnction;} Public static void closesession () throws hibernateException {session session = (session) threadlocal.get (); threadLocal.Set (null); if (session! = null) {sessio n.close ();}}}}}}}}}}}} private hibernateFactory ()}
} 3. Establish a CAT table PO (persistent object) to generate Cat.cfg.xml, Cat.java, AbstractCat.java process and the process of generating hibernate.cfg.xml and HibernateFactory.java can be completed by MyEClipse. Cat.cfg.xml XML Version = "1.0"?>
/ * * Created thu feb 17 16:11:44 cst 2005 by myeclipse hibernate Tool. * / Package com.mdcl.vo;
Import java.io.serializable;
/ ** * A class that represents a row in the 'cat' table. * This class may be customized as it is never re-generated * after being created. * / Public class Cat extends AbstractCat implements Serializable {/ ** * Simple CONSTRUctor of cat instances. * / public cat () {}
/ * (non-javadoc) * @see com.mdcl.vo.abstractcat # getcatid () * / public string getcatid () {// Todo auto-generated method stub return super.getcatid ();} / * (non- Javadoc) * @see com.mdcl.vo.abstractcat # getName () * / public string getname () {// Todo auto-generated method stub return super.getname ();} / * (non-javadoc) * @see Com.mdcl.vo.abstractcat # getsex () * / public string getsex () {// Todo auto-generated method stub return super.getSex ();} / * (non-javadoc) * @see com.mdcl.vo .ABSTRACTCAT # getWeight () * // * (Non-javadoc) * @see com.mdcl.vo.abstractcat # setcatid (java.lang.string) * / public void setcatid (String catid) {// Todo Auto-generated Method stub super.setcatid (catid);} / * (non-javadoc) * @see com.mdcl.vo.abstractcat # setname (java.lang.string) * / public void setname (String name) {// Todo Auto -Generated method stub super.setname (Name);} / * (non-javadoc) * @see com.mdcl.vo.abstractcat # setsex (java.lang.string) * / public void setsex (string sex) {//// Todo Auto-GE Nerated method stub super.setsex (sex);} / * (non-javadoc) * @see com.mdcl.vo.abstractcat # setWeight (java.lang.integer) * /
/ * (Non-javadoc) * @see java.lang.object # hashcode () * / public int 6code () {// Todo auto-generated method stub return super.hashcode ();} / * (non-javadoc) * @see java.lang.object # femance () * / protected void finalize () throws throwable {// Todo auto-generated method stub super.Finalize ();} / * (non-javadoc) * @see java.lang .Object # clone () * / protected Object clone () throws CloneNotSupportedException {// TODO Auto-generated method stub return super.clone ();} / * (non-Javadoc) * @see java.lang.Object # equals ( Java.lang.Object) * / public boolean equals (object obj) {// Todo auto-generated method stub return super.equals (obj);} / * (non-javadoc) * @see java.lang.object # toString () * / Public string toString () {// Todo auto-generated method stub return super.tostring ();} / ** * Constructor of cat instances given a simple primary key. * @Param catid * / public cat (java .lang.string catid) {super ();} / * add customized code below * /
} AbstractCat.java/* * WARNING:... DO NOT EDIT THIS FILE This is a generated file that is synchronized * by MyEclipse Hibernate tool integration * * Created Sat Feb 19 12:00:50 CST 2005 by MyEclipse Hibernate Tool * / Package com.mdcl.vo;
Import java.io.serializable;
/ ** * a class this represents a row in the cat table. * You can customize the behavior of this class by editing the class, {@link cat ()}. * Warning: do not edit this file. This is a recogn . file that is synchronized * by MyEclipse Hibernate tool integration * / public abstract class AbstractCat implements Serializable {/ ** The cached hash code value for this instance Settting to 0 triggers re-calculation * / private int hashValue = 0..;
/ ** The composite primary key value. * / Private java.lang.string catid; / ** The value of the simple name property. * / Private java.lang.string name;
/ ** the value of the simple sex property. * / Private java.lang.string sex;
/ ** * Simple constructor of abstractcat instances. * / Public abstractcat () {}
/ ** * Constructor of Abstractcat Instances Given a Simple Primary Key. * @Param Catid * / Public Abstractcat (Java.lang.String Catid) {this.setcatid (CAcid);
/ ** * Return The Simple Primary key value That Identifies this object. * @Return java.lang.string * / public java.lang.string getcatid () {return catid;}
/ ** * set the Simple primary key value That Identifies this object. * @Param catid * / public void setcatid (java.lang.string catid) {this.hashvalue = 0; this.catid = catid;}
/ ** * Return the value of the name column. * @Return java.lang.string * / public java.lang.string getName () {Return this.name;}
/ ** * set the value of the name column. * @Param name * / public void setName (java.lang.string name) {this.name = name;}
/ ** * Return the value of the sex column. * @Return java.lang.string * / public java.lang.string getsex () {return this.sex;}
/ ** * set the value of the sex column. * @Param sex * / public void setsex (java.lang.string sex) {this.sex = sex;}
/ ** * Implementation of the equals comparison on the basis of equals comparison on the basis of equals. * @Param rhs * @return boolean * / public boolean equals (object rhs) {if (rhs == null) Return False; if ( (RHS Instanceof Cat) Return False; Cat That = (CAT) RHS; IF (this.getcatid ()! = null && That.getcatid ()! = NULL) {if (! this.getcatid (). Equals. that.getCatId ())) {return false;}} return true;.} / ** * Implementation of the hashCode method conforming to the Bloch pattern with * the exception of array properties (these are very unlikely primary key types) * @ Return Int * / Public INT HashCode () {if (this.hashvalue == 0) {int result = 17; int CatidValue = this.getcatid () == null? 0: this.getcatid (). hashcode (); result = Result * 37 CatidValue; this.hashvalue = Return this.hashvalue;}} 4. Write an example to test servlettest.java/* * created on 2005-2-19 * * Todo to change the template for this generated file go to * window - preferences - java - Code style - code templates * / package com.mdcl.test;
Import java.io.ioException; import java.io.printwriter;
Import javax.servlet.ServletException; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse;
Import net.sf.hibelption; import net.sf.hibernate.Session; import net.sf.hibernate.transaction;
Import org.apache.log4j.logger;
import com.mdcl.hibernate.HibernateFactory; import com.mdcl.vo.Cat; / ** * @author a * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates * / public class servlettest extends httpservlet {
/ ** * deStruction of the servlet.
* / private static logger log = logger.getlogger (servlettest.class); public void destroy () {super.destroy (); // Just Puts "Destroy" string in log // put your code here}
/ ** * The doget method method of the servlet.
* * this method is called when a form is it. * * @Param Request the Request Send by the client to the server * @Param Response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred * / public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response);
}
/ ** * The dopost method of the servlet.
* * this method IS Called When a form HAS ITS TAG VALUE METHOD Equals to post. * * @Param Request the Request Send by The Client To the Server * @Param Response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred * / public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Response.setContentType ("text / html"); printwriter out = response.getwriter (); out .println ("") Out.println (""); OUT.Println ("
} Ok, complete Hibernate travel. Don't you understand? Reference Hibernate Chinese Documentation Hibernate Chinese Site Http://www.hibernate.org.cn/