小试Hibernate3.0+eclipse 3.1M4
王伟东
环境如下
- Eclipse 3.1M4: http://www.eclipse.org
- JBoss Eclipse IDE 1.4.x: http://www.jboss.org/
- Hibernate 3.0 beta3: http://prdownloads.sourceforge.net/hibernate
- Hibernate Tools 3.0 alpha 1: http://www.hibernate.org/Projects/HibernateTools
- Jdk 1.4.2
插件
关于Hibernator tools在hibernate开发的Eclipse下的插件
示例
Hibernate和Hibernator tools的文档非常齐全(英文)
Hibernator tools的用法就更简单了还有一个Flash向导 : http://www.hibernate.org/hib_docs/tools/viewlets/createcfgxml_viewlet_swf.html
根据Flash向导很容易就得到其相应的Project,关于数据库的选用根据你自己的喜好了,我是用的SQL Server
通过*.hbm.xml存放在相应的Java文件目录且名字相同如下:
User.java
Users.hbm.xml
注意hibernate.cfg.xml的位置根据你的实际环境正确放置,比如我用的是tomcat工程的目录结构,我就放在了WEB-INF\classes下面如下:
GeneralHbmSettings.hbm.xml
hibernate.cfg.xml
接下来写测试范例:
package test;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.*;
import org.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) {
// Make sure you log the exception, as it might be swallowed
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();
}
}
test.java
//下面数据库对象及方法换成你自己的
package test;import hib.user.Users;import org.hibernate.*;public class Test {public static void main(String[] args) {
try {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Users userInfo = new Users();
userInfo.setLogonId("userid" );
userInfo.setEmailAddress("wweidong@sina.com");
session.save(userInfo);
tx.commit();
HibernateUtil.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
}
好了一切就绪Run一下试试却报如下错误
(Unsupported major.minor version 49.0)......
原来网站上下来的hibernate3.jar是在JDK 1.5下编译的,当运行在JDK 1.4就会报如上错误,但是我有好多工程都是在JDK 1.4下,目前又不想升级,查了一下资料发现hibernate3的source file没有用到J2se 1.5的新功能,OpenSource的好处就来了,用Jdk 1.4自己build一下hibernate3.jar,替换掉原来了再运行就通过了。


06年热贴
