hibernate配置笔记

来源:互联网 发布:网络歌手男 编辑:程序博客网 时间:2024/05/05 18:07

 一个配置的例子:
1.先在数据库中建立一个表cat
create table cat(
cat_id varchar(20) PRIMARY KEY not null,
name varchar(20) not null,
sex char(1))
2.建立hibernate.cfg.xml并生成hibernaetFactory.class管理他
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
          "
http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration.                   -->
<hibernate-configuration>

    <session-factory>
        <!-- properties -->
        <property name="connection.username">root</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
        <property name="connection.password"></property>
        <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>

        <!-- mapping files -->
        <mapping resource="com/mdcl/vo/Cat.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
HibernaetFactory.java
package com.mdcl.hibernate;

import net.sf.hibernate.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.<br><br>
     * Examples: <br>
     * <code>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(CONFIG_FILE_LOCATION);
              sessionFactory = cfg.buildSessionFactory();
            } catch (Exception e) {
              System.err
        .println("%%%% Error Creating HibernateSessionFactory %%%%");
              e.printStackTrace();
            }
          }
          session = sessionFactory.openSession();
          threadLocal.set(session);
        }
        return session;
      }
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }
    private HibernateFactory() {
    }

}
3.建立cat表的po(持久对象),生成cat.cfg.xml,cat.java,AbstractCat.java的过程和上面生成hibernate.cfg.xml和hibernateFactory.java的过程可以由myeclipse协助完成。
cat.cfg.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
                            "
http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration.                   -->
<!-- Created Sat Feb 19 12:00:50 CST 2005                         -->
<hibernate-mapping package="com.mdcl.vo">

    <class name="Cat" table="cat">
        <id name="catId" column="cat_id" type="java.lang.String">
            <generator class="uuid.hex"/>
        </id>
 
        <property name="name" column="name" type="java.lang.String"  not-null="true" />
        <property name="sex" column="sex" type="java.lang.String" />
    </class>
   
</hibernate-mapping>
cat.java

/*
 * 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-generated 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 hashCode() {
  // TODO Auto-generated method stub
  return super.hashCode();
 }
 /* (non-Javadoc)
  * @see java.lang.Object#finalize()
  */
 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 that 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 generated 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(catId);
    }

    /**
     * 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 equality of the primary key values.
     * @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 = result;
        }
        return this.hashValue;
    }
}
4.编写一个例子测试一下
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.hibernate.HibernateException;
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. <br>
  */
 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 of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @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. <br>
  *
  * 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("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
  out.println("<HTML>");
  out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println("  <BODY>");
  out.print("    This is ");
  out.print(this.getClass());
  try {
   log.info("........servletTest.doPost()....start");
   Session session =HibernateFactory.currentSession();
   Transaction tx = session.beginTransaction();
        Cat cat = new Cat();
        cat.setCatId("4");
        cat.setName("Karl");
        cat.setSex("F");
        session.save(cat);
        tx.commit();
    } catch (HibernateException e) {
         e.printStackTrace();
         log.error("........servletTest.doPost()....error");
       }
  log.debug("start");
  out.println(", using the POST method");
  out.println("  </BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
  log.info("........servletTest.doPost()....end");
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
 public void init() throws ServletException {
  // Put your code here
 }

}
 

原创粉丝点击