Hibernate QuickStart

本文介绍了基于JBuilder X、MySQL 4.1和hibernate - 3.0的开发环境搭建。需配置hibernate.jar及相关库,设置工程属性包含这些库。还新建了CatServlet,在quickstart/src目录新建hibernate.cfg.xml文件进行Hibernate配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发环境

工具: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>
持久类Cat
package 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);

辅助类HibernateTool
package 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();
        }
    }
}
Sevlet
package 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,选Copy
TroubleShooting
可能出现的问题及解决方案:
1. NoClassDefinition
加入库aspectjr.jar到工程的lib中(在mysql-connector的src/lib下有)
2. NullPointerException (XXX.preparedstatement)
使用3.0版本的MySQL connector库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值