Welcome 微信登录

首页 / 软件开发 / JAVA / Hibernate Annotations实战--从hbm.xml到Annotations

Hibernate Annotations实战--从hbm.xml到Annotations2011-07-28从 hbm.xml 到 Annotations

下面让我们先看一个通常用 hbm.xml 映射文件的例子. 有3个类 .HibernateUtil.java 也就是 Hibernate文档中推荐的工具类,Person.java, Test.java 测试用的类.都在test.hibernate 包中. 每个类的代码如下:

HibernateUtil:

01 package test.hibernate;
02
03 import org.hibernate.HibernateException;
04 import org.hibernate.Session;
05 import org.hibernate.SessionFactory;
06 import org.hibernate.cfg.Configuration;
07
08 public class HibernateUtil {
09 public static final SessionFactory sessionFactory;
10
11 static {
12 try {
13 sessionFactory = new Configuration()
14 .configure()
15 .buildSessionFactory();
16 } catch (HibernateException e) {
17 // TODO Auto-generated catch block
18
19 e.printStackTrace();
20 throw new ExceptionInInitializerError(e);
21 }
22 }
23
24 public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
25
26 public static Session currentSession() throws HibernateException {
27 Session s = session.get();
28
29 if(s == null) {
30 s = sessionFactory.openSession();
31 session.set(s);
32 }
33
34 return s;
35 }
36
37 public static void closeSession() throws HibernateException {
38 Session s = session.get();
39 if(s != null) {
40 s.close();
41 }
42 session.set(null);
43 }
44 }