package com.db;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Log log =
LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try {
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() {
Session s = (Session) session.get();
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}
后面将会提到如何使用HibernateUtil,下面建立我们所需的数据库
(略)我们可以使用208上的db_test_account这个数据库中的表message来测试我们的Hibernate配置是否成功。数据库样例:
建表语句:
CREATE TABLE `message` ( `Id` varchar(50) NOT NULL default '0', `text` varchar(50) default NULL, `nextMessage` int(4) default NULL, PRIMARY KEY (`Id`) ) TYPE=MyISAM
创建O/R Mapping:
点击Edit
点击New添加MySQL的驱动,保存
激活Database Explorer,保存。
选择Database Explorer,创建数据库链接:
点击创建新的数据库,添加所需必要的参数
保存,然后右键点击该数据库选择open database,测试是否配置成功,如果不能连接查看该连接的配置参数。
点 击完成后MyEclipse会自动生成POJO和Map文件,并更新Hibernate的配置文件(主要是加载Map文件)。ID Generator选项可以根据你的需要进行选择,具体含义请参阅hibernate官方文档。下面建立一个测试用的jsp页面来看看Hibernate 是否好用。
//MyJsp.jsp
String path = request.getContextPath();
String basePath = request.getScheme()+":
//"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'MyJsp.jsp' starting page
<!--
-->
org.hibernate.Session s = HibernateUtil.currentSession();
String hql = " from Message where text='b'";
try {
org.hibernate.Query query = s.createQuery(hql);
java.util.List msgList = query.list();
hello.Message msg = (hello.Message) msgList.get(0);
out.println(msg.getId());
out.println(msg.getText());
out.println(msg.getNextmessage());
} catch (org.hibernate.HibernateException e) {
e.printStackTrace();
}
HibernateUtil.closeSession();
%>
正常的结果如下:
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/374079/viewspace-131228/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/374079/viewspace-131228/