在Tomcat下配置Hibernate的开发环境
http://tech.ddvip.com 2007年08月22日 社区交流
内容摘要:今天花了几个小时,终于将机房里面的Tomcat+Hibernate的开发、学习环境配置好了。
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()+" " + cat.getName() + "<br>");
}
tx.commit();
HibernateUtil.closeSession();
out.println("Done.");
%>
</body>
</html>说明:
1.对HibernateUtil.java的编译:
javac -classpath ../lib/hibernate2.jar HibernateUtil.java
有2个警告,可以忽略之。
责编:豆豆技术应用
正在加载评论...