在Tomcat下配置Hibernate的开发环境
这是实战JSP进阶编程之三。
今天花了几个小时,终于将机房里面的Tomcat+Hibernate的开发、学习环境配置好了。
应用场景:Tomcat 5.5, Hibernate 2.1.7, Mysql 3.23.43, Mysql Driver:3.0.14, JDK: 1.4.2 OS: TurboLinux Server 8.0
用户环境:普通学生帐户--j2ee,位置: /home/j2ee/public_html

为了方便初学者,本教程特意作了简化处理。
1。将hibernate2.jar,dom4j,ehcache,cglib等Hibernate手册上说的那些jar copy 到 WEB-INF/lib里面。

2。将hibernate.cfg.xml copy 到WEB-INF里面。
内网用户只要直接从/home/j2ee/public_html/WEB-INF中copy就可以了。
外面的读者也只需要在hibernate.cfg.xml中改改MySQL的参数就可以了。
3. 本例对通行的Cat例子,进行了进一步的简化,只有2个字段:
CAT_ID varchar(50), name varchar(50)。
4. WEB-INF/hb中有如下文件:
Cat.java
Cat.hbm.xml
HibernateUtil.java
5. 2个用于测试的jsp文件:
addCat.jsp
getCats.jsp

具体文件如下:
第一个文件:hibernate.cfg.xml

<?xml version="1.0" encoding="GB2312" ?>
<!DOCTYPE hibernate-configuration (View Source for full doctype...)>
- <hibernate-configuration>
- <session-factory>
<property name=
"hibernate.connection.driver_class"]com.mysql.jdbc.Driver</property>
<property name=
"hibernate.connection.url"]jdbc:mysql://localhost/joke</property>
<property name=
"hibernate.connection.username"]root</property>
<property name=
"hibernate.connection.password"]
<property name=
"show_sql"]false</property>
<property name=
"dialect"]net.sf.hibernate.dialect.MySQLDialect</property>
<mapping resource=
"hb/Cat.hbm.xml"]
</session-factory>
</hibernate-configuration>

第二个文件:Cat.java

package hb;

public class Cat {

private String id;
private String name;

public Cat() {
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String toString() {
String strCat = new StringBuffer()
.append(this.getId()).append(
", ")
.append(this.getName()).append(
", ")
.toString();

return strCat;
}
}

第三个文件:Cat.hbm.xml

<?xml version=
"1.0" ?>
<!DOCTYPE hibernate-mapping (View Source for full doctype...)>
- <hibernate-mapping default-cascade=
"none" default-access="property" auto-import="true"]
- <class name=
"hb.Cat" table="cat" mutable="true" polymorphism="implicit" dynamic-update="false" dynamic-insert="false" batch-size="1" select-before-update="false" optimistic-lock="version"]
- <id name=
"id" type="java.lang.String" unsaved-value="null"]
<column name=
"CAT_ID" sql-type="varchar(32)" not-null="true"]
<generator class=
"uuid.hex"]
</id>
- <property name=
"name" not-null="false" unique="false" update="true" insert="true"]
<column name=
"NAME" sql-type="varchar(20)" not-null="true"]
</property>
</class>
</hibernate-mapping>

第四个文件:HibernateUtil.java


package hb;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: "
+ ex.getMessage(), ex);
}
}


public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {
// Session s;
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();
}

}


第五个文件: addCat.jsp


<%@ page contentType=
"text/html; charset=GB18030" %>
<%@ page import=
"hb.*, net.sf.hibernate.*" %>
<html>
<head>
<title>test</title>
</head>
<body bgcolor=
"#ffffff"]
<h1>Test Hibernate</h1>
<a href=
"getCats.jsp"]View Cats[/url]<br>
<%
if(request.getParameter(
"Go") != null) {
String name = request.getParameter(
"name");
if(name == null || name.length() < 1) {
out.println(
"Name can not be empty!");
return;
}
SessionFactory sessionFactory;
net.sf.hibernate.Session hsession = HibernateUtil.currentSession();

Transaction tx = hsession.beginTransaction();
Cat c;
c = new Cat();
c.setName(name);
hsession.save(c);
hsession.flush();

tx.commit();

HibernateUtil.closeSession();
out.println(
"Done.");
}
%>
Add New Cats:<br>
<form method=post action=addCat.jsp>
Name:<input name=name><br>
<input type=submit name='Go' value='Add'><br>
</form>
</body>
</html>


第六个文件: getCats.jsp


<%@ page contentType=
"text/html; charset=GB18030" %>
<%@ page import=
"hb.*, net.sf.hibernate.*,
java.util.*
" %>
<html>
<head>
<title>Hibernate Test</title>
</head>
<body bgcolor=
"#ffffff"]
<h1>Test Hibernate</h1>
<a href=addCat.jsp>Add Cat[/url]<br>
<p> ID Name </p>
<%
SessionFactory sessionFactory;
net.sf.hibernate.Session hsession;
hsession = HibernateUtil.currentSession();

Transaction tx = hsession.beginTransaction();

Query query = hsession.createQuery (
"select cat from Cat as cat ");

for (Iterator it = query.iterate(); it.hasNext();) {
Cat cat = (Cat) it.next();
out.println(cat.getId()+
"&nbsp; " + cat.getName() + "<br>");
}

tx.commit();

HibernateUtil.closeSession();
out.println(
"Done.");
%>
</body>
</html>


说明:
1.对HibernateUtil.java的编译:
javac -classpath ../lib/hibernate2.jar HibernateUtil.java
有2个警告,可以忽略之。
2.
内网观测点

hofman   2005-04-04 02:05:07 评论:8   阅读:4307   引用:0
回复cf @2005-05-26 18:19:50  hofman
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*,这两个包都在hibernate2.jar里面,属于hibernate最基本的包。
无题 @2005-05-26 15:12:07  cf
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*这两句怎么解释, 怎么导入呢, 在hibernate的那个目录下啊?
无题 @2005-04-06 22:59:08  lunzi
学校的学习环境就是好,真有点怀念在学校学习的时间,现在想好好的学,没有以前那么充足的时间了。
道谢! @2005-04-05 18:48:42  xiaosheng
通过这个实例,以前看Hibernate文档一头雾水!现在总算能看懂一些!谢谢hofman.
我搞定了! @2005-04-05 10:09:03  xiaosheng
原来是
<!DOCTYPE hibernate-mapping (View Source for full doctype...)>这儿的问题!
从道理上讲 @2005-04-04 23:33:43  xiaosheng
从道理上讲这段代码放到jboss服务器中也应该能运行!为什么它会提示StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw Exception java.lang.NoClassDefFoundError这个错误呢?
Hibernate的特点 @2005-04-04 19:13:31  hofman
id对应CAT_ID,可以是别的,可以用catid取代id,与数据表无关。这一点不影响。因为hibernate看到的是object/property(instance),而不是table/field。
疑问?? @2005-04-04 18:22:31  jason
这其中的表是cat,字段是CAT_ID varchar(50), name varchar(50)
那么Cat.java中的id又是什么呀?

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

2003-2007@copyright