关于服务器Tomcat和数据库MySQL的安装配置参见本人上一篇文章
《在Windows 2000 Server安装配置Tomcat+MySQL》
在Tomcat上建立独立的服务myService
0.set %WebApp% = $Tomcat_HOME$/webapps/myService
1 在$Tomcat_HOME$/webapps下创建目录结构
myService
+-----WEB-INF
+-----lib
+-----class
+-----net
+-----sf
+-----hibernate
+-----examples
+-----quickstart
2 在Tomcat的server.xml($Tomcat_HOME$/conf)中为此服务配置独立的Context
<Context className="org.apache.catalina.core.StandardContext" cachingAllowed="true" charsetMapperClass="org.apache.catalina.util.CharsetMapper" cookies="true" crossContext="false" debug="0" displayName="Welcome to Tomcat" docBase="C:\Tomcat4.1\webapps\myService" mapperClass="org.apache.catalina.core.StandardContextMapper" path="/myService" privileged="false" reloadable="false" swallowOutput="false" useNaming="true" wrapperClass="org.apache.catalina.core.StandardWrapper">
<Resource name="jdbc/mysqltest" scope="Shareable" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/mysqltest">
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>4</value>
</parameter>
<parameter>
<name>password</name>
<value>test</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/study</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
<parameter>
<name>username</name>
<value>test</value>
</parameter>
</ResourceParams>
<ResourceLink name="jdbc/mysqltest" global="jdbc/mysqltest" type="javax.sql.DataSourcer"/>
</Context>
3 解压下载的压缩包hibernate-2.1.2.zip,将解压出来的hibernate2.jar复制到%WebApp%/WEB-INF/lib
4 将解压出来的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
5 编写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/mysqltest</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>
*connection.datasource的名称必须和[Config Tomcat DBCP for Mysql]配置中server.xml的context指定的DBCP的名称一致。
6 编写第一个测试代码
6.1 将以下代码保存为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;
}
}
6.2 将以下代码保存为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>
6.3 将以下代码保存为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();
}
}
6.4 将以下代码保存为testcat.jsp,放入%WebApp%
<%@ 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("chenm");
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>
6.5 用http测试,http://localhost:8090/myService/testcat.jsp
测试结果,看见:Female Cat: chenm