您的位置:首页 > 产品设计 > UI/UE

Hibernate QuickStart

2005-07-13 20:31 316 查看
开发环境
工具:JBuilder X 
数据库:MySQL 4.1
版本:hibernate-3.0
配置库
需要hibernate.jar以及hibernate/lib下的几个库
MySQL JDBC Driver
设置工程属性,使其包含这些库。
Web Module
新建一个CatServlet
Hibernate配置
在quickstart/src目录中新建文件hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.password">8888</property>
<property name="connection.url">jdbc:mysql://localhost:3306/quickstart</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="show_sql">false</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Mapping files -->
<mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration> 持久类Catpackage net.sf.hibernate.examples.quickstart;public class Cat {
    private String id;
    private String name;
    private char sex;
    private float weight;
    public Cat() {
    }    public String getId() {
        return id;
    }    private void setId(String id) {
        this.id = id;
    }    public String getName() {
        return name;
    }    public void setName(String name) {
        this.name = name;
    }    public char getSex() {
        return sex;
    }    public void setSex(char sex) {
        this.sex = sex;
    }    public float getWeight() {
        return weight;
    }    public void setWeight(float weight) {
        this.weight = weight;
    }}
映射文件Cat.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">
<hibernate-mapping>
  <class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">
    <!--
      A 32 hex character is our surrogate key. It's automatically
      generated by Hibernate with the UUID pattern.
    -->
    <id name="id" type="string" unsaved-value="null">
      <column name="CAT_ID" sql-type="char(32)" not-null="true"/>
      <generator class="uuid.hex"/>
    </id>
    <!-- A cat has to have a name, but it shouldn' be too long. -->
    <property name="name">
      <column name="NAME" length="16" not-null="true"/>
    </property>
    <property name="sex"/>
    <property name="weight"/>
  </class>
</hibernate-mapping>
数据库CREATE DATABASE quickstart;
CREATE TABLE Cat (cat_id VARCHAR(32), name VARCHAR(20),
   sex CHAR(1), weight real, PRIMARY KEY (cat_id));
INSERT INTO Cat VALUES ('234875','Diane','f',34.2);

辅助类HibernateToolpackage net.sf.hibernate.examples.quickstart;import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; public class HibernateTool {    private static Log log = LogFactory.getLog(HibernateTool.class);    private static final SessionFactory sessionFactory;    static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure().
                             buildSessionFactory();
        } catch (Throwable ex) {
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }    public static final ThreadLocal session = new ThreadLocal();    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null) {
            s.close();
        }
    }
}
Sevletpackage net.sf.hibernate.examples.quickstart;import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;
import org.hibernate.HibernateException;
public class CatServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=Big5";
    //private HibernateTool hibernateUtil = null;    //Initialize global variables
    public void init() throws ServletException {
    }    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();        // hibernateUtil = new HibernateTool();
        try {
            Session session = HibernateTool.currentSession();
            Transaction tx = session.beginTransaction();
            Cat princess = new Cat();
            princess.setName("Princess");
            princess.setSex('F');
            princess.setWeight(7.4f);            session.save(princess);
            tx.commit();            Query query = session.createQuery(
                    "select c from Cat as c where c.sex = :sex");
            query.setCharacter("sex", 'F');            out.println("<html>");
            out.println("<head><title>Cat</title></head>");
            out.println("<body bgcolor=/"#ffffff/">");            for (Iterator it = query.iterate(); it.hasNext(); ) {
                Cat cat = (Cat) it.next();
                out.println("<p>Female Cat: " + cat.getName() + "</p>");
            }            out.println("</body>");
            out.println("</html>");
            out.close();            tx.commit();            HibernateTool.closeSession();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }    //Process the HTTP Put request
    public void doPut(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
    }    //Clean up resources
    public void destroy() {
    }
}
布署设置工程属性,Build-Resource-xml,选CopyTroubleShooting可能出现的问题及解决方案:
1. NoClassDefinition加入库aspectjr.jar到工程的lib中(在mysql-connector的src/lib下有)
2. NullPointerException (XXX.preparedstatement)使用3.0版本的MySQL connector库
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息