JBuilder+Hibernate+Tomcat快速入门
高科华
作者简介:高科华,南京航空学院计算数学专业硕士,有十年以上的企业信息化工作经验。目前的研究兴趣,J2EE企业应用、ERP软件研发、数据仓库系统研发。
作者声明:本文没有最后定稿。
本文给出了用JBuilder开发Hibernate+Tomcat Web应用的一般步骤。
1. 下载hibernate-2.1.x.zip
http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc
2. 安装,将zip文件解压到JBuilder_HOME\ thirdparty
3. 在JBuilder2005中新建hibernate库,选择菜单Tools-Configure-Libraries,在弹出的对话框中点击New按钮,输入hibernate库的名称:hibernate,点击Add按钮,将hibernate目录中的文件hibernate2.jar增加到hibernate库中,根据需要将hibernate\lib目录中的相应的*.jar增加到hibernate库中,一般需要这些类库:dom4j、CGLIB、Commons Collections、Commons Logging、ODMG4、EHCache
4. 新建工程文件,选菜单File-New Project,给工程文件取名为myProject
设置工程文件的属性,选菜单Project-Project Properties,选择Tomcat作为服务器,将hibernate库加入Path/Required Libraries。
5. 新建Web模块,选菜单File-New,给Web模块取名为quickstart
6. 用servlet向导新建一个servlet文件,选菜单File-New,在弹出的对话框中选择Web-Standard Servlet,取名为Servlet1,在向导的第五步选择Create a runtime configuration
7. 运行Servlet1
8. 将quickstart\Tomcat\conf目录中的文件server8080.xml加入工程文件,修改server8080.xml的内容
<?xml version="1.0" encoding="UTF-8"?>
<Server debug="0" port="8081" shutdown="SHUTDOWN">
<Service name="Catalina">
<Connector acceptCount="10" connectionTimeout="60000" debug="0" maxThreads="75" minSpareThreads="5" port="8080"/>
<Engine debug="0" defaultHost="localhost" name="Catalina">
<Host appBase="C:\jbproject\quickstart\Tomcat\webapps" autoDeploy="false" debug="0" deployXML="false" name="localhost" unpackWARs="false">
<!--Context debug="0" docBase="C:\jbproject\quickstart\quickstart" path="/quickstart" reloadable="true" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart"/-->
<Context path="/quickstart" docBase="C:\jbproject\quickstart\quickstart" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart">
<Resource name="jdbc/quickstart" scope="Shareable" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/quickstart">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- DBCP database connection settings -->
<parameter>
<name>url</name>
<value>jdbc:hsqldb:hsql://localhost</value>
<!--value>jdbc:microsoft:sqlserver://nt04:1433;DatabaseName=test</value-->
</parameter>
<parameter>
<name>driverClassName</name>
<value>org.hsqldb.jdbcDriver</value>
<!--value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value-->
</parameter>
<parameter>
<name>username</name>
<value>sa</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<!-- DBCP connection pooling options -->
<parameter>
<name>maxWait</name>
<value>3000</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>100</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>
</ResourceParams>
</Context>
</Host>
</Engine>
</Service>
</Server>
9. 设置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-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:comp/env/jdbc/quickstart</property>
<property name="show_sql">false</property>
<property name="dialect">net.sf.hibernate.dialect.PostgreSQLDialect</property>
<!-- Mapping files -->
<mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
10. 新建一个持久类
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;
}
}
11. 在quickstart\src目录中新建影射文件cat.hbm.xml如下:
<?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>
12. 准备数据库
13. 新建一个类HibernateUtil
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();
}
}
14. 修改Servlet1.java
package net.sf.hibernate.examples.quickstart;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Query;
public class Servlet1 extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=Big5";
private HibernateUtil 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 HibernateUtil();
try {
Session session = hibernateUtil.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>Servlet1</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();
HibernateUtil.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() {
}
}
15. 再次运行Servlet1,报错。
16. 设置工程文件的属性,选菜单Project-Project Properties,在弹出的对话框中选择Build-Resource-xml,选择选择按钮Copy。这一步是为了在重建工程文件时把src目录中的xml文件拷贝到classes目录中。
17. 再次运行Servlet1,你将看到使用了hibernate后的显示结果。
“hibernate.cfg.xml not found”。
用JUnit测试时,文件hibernate.cfg.xml中需增加如下内容:
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="username">sa</property>
<property name="password"></property>
<property name="connection.provider_class"> net.sf.hibernate.connection.DBCPConnectionProvider</property>
<property name="connection.pool_size">50</property>
<property name="dbcp.maxActive">100</property>
<property name="dbcp.whenExhaustedAction">1</property>
<property name="dbcp.maxWait">120000</property>
<property name="dbcp.maxIdle">10</property>
参考资源
http://www.hibernate.org/hib_docs/reference/en/html/quickstart.html