Hibernate的手册里的Cat例子感觉很不明了,很难照着它轻松的运行起第一个例子,费了点周折,总算看到一点结果,如果你是新手,可以参考一下,少走一些弯路。
1.下载tomcat和Hibernate
Tomcat 5.0.27
http://apache.linuxforum.net/dist/jakarta/tomcat-5/v5.0.27/bin/jakarta-tomcat-5.0.27.zip
Tomcat 5.0.28
http://apache.linuxforum.net/dist/jakarta/tomcat-5/v5.0.28/bin/jakarta-tomcat-5.0.28.zip
Hibernate2.1.6
http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc2. 安装
以tomcat+mysql+hibernate为例
tomcat的安装,及mysql的安装和DBCP的配制参见http://blog.csdn.net/ahxu/archive/2004/09/01/91611.aspx,这里就不提了,这里假设tomcat+mysql已经配置并测试可用,这里%WebApp%代表你已配置好的一个web应用的root,着重说一下hibernate的安装,
1) 解压下载的压缩包,将解压出来的hibernate2.jar复制到%WebApp%/WEB-INF/lib
2) 将解压出来的lib目录下的
cglib-full-2.0.2.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.4.jar
ehcache-0.9.jar
jta.jar
log4j-1.2.8.jar
odmg-3.0.jar
文件同样复制到%WebApp%/WEB-INF/lib,具体请参见解压出来的lib目录下的readme.txt。
3) 将解压出来的etc目录下的
log4j.properties
文件复制到%WebApp%/WEB-INF/classes。
3.编写相关文件
1) 按照参考文档,配置hibernate,将以下代码保存为hibernate.cfg.xml放在%WebApp%/WEB-INF/classes下
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:comp/env/jdbc/mysql</property>
<property name="show_sql">false</property>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<!-- Mapping files -->
<mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
NOTE:这里与hibernate文档里的不一样,这里指定数据源为mysql数据库jdbc/mysql,方言dialect为net.sf.hibernate.dialect.MySQLDialect。
2) 将以下代码保存为Cat.java,并生成相应的Cat.class,放入%WebApp%/WEB-INF/classes,这里无论你用什么方法生成Cat.class,但最终Cat.class应在%WebApp%/WEB-INF/classes/net/sf/hibernate/examples/quickstart目录下
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;
}
}
3) 将以下代码保存为O/R映射文件Cat.hbm.xml,放入%WebApp%/WEB-INF/classes
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.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
4) 在数据库内建表,结构如下
Column | Type | Modifiers
--------+-----------------------+-----------
cat_id | character(32) | not null
name | character varying(16) | not null
sex | character(1) |
weight | real |
Indexes: cat_pkey primary key btree (cat_id)
5) 将以下代码保存为HibernateUtil.java,并生成相应的HibernateUtil.class,放入%WebApp%/WEB-INF/classes,同样注意package
package net.sf.hibernate.examples.quickstart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.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();
}
}
NOTE:这里与hibernate文档也不同,原文档编绎时缺少2个包,这里已加上。
6) 将以下代码保存为test.jsp,放入%WebApp%/,用http测试
<%@ page language="java" pageEncoding="GB2312" %>
<%@ page import="net.sf.hibernate.Transaction"%>
<%@ page import="net.sf.hibernate.Session"%>
<%@ page import="net.sf.hibernate.cfg.*"%>
<%@ page import="net.sf.hibernate.Query"%>
<%@ page import="net.sf.hibernate.examples.quickstart.HibernateUtil"%>
<%@ page import="net.sf.hibernate.examples.quickstart.Cat"%>
<%@ page import="java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>Lomboz JSP</title>
</head>
<body bgcolor="#FFFFFF">
<%
//添加一只Cat
Session ses = HibernateUtil.currentSession();
Transaction tx= ses.beginTransaction();
Cat princess = new Cat();
princess.setName("ahxu");
princess.setSex('F');
princess.setWeight(7.4f);
ses.save(princess);
tx.commit();
HibernateUtil.closeSession();
//读取库里所有Cat
ses = HibernateUtil.currentSession();
tx= ses.beginTransaction();
Query query = ses.createQuery("select c from Cat as c where c.sex = :sex");
query.setCharacter("sex", 'F');
for (Iterator it = query.iterate(); it.hasNext();) {
Cat cat = (Cat) it.next();
out.println("Female Cat: " + cat.getName() );
}
tx.commit();
HibernateUtil.closeSession();
%>
</body>
</html>
小结
步骤基本与原文档步骤相同,只是做了一些补充,方便上手,这里并没有对其中的一些配置做具体解释,如有疑问请参见发行包中的相关文档。
以上tomcat5.027 + hibernate2.1.6测试通过
附:
Tomcat官方网站 http://jakarta.apache.org/tomcat/index.html
Hibernate官方网站 http://www.hibernate.org
Hibernamte非官方中文网 http://www.hibernate.org.cn
mysql官方图形化管理工具Graphical clients -- different GUI interfaces to administer MySQL and data
MySQL Control Center (no longer under development)