WEB开发网
开发学院WEB开发Jsp Hibernate Annotations 实战介绍 阅读

Hibernate Annotations 实战介绍

 2008-01-05 09:40:46 来源:WEB开发网   
核心提示: 从 hbm.xml 到 Annotations下面让我们先看一个通常用 hbm.xml 映射文件的例子. 有3个类 .HibernateUtil.java 也就是 Hibernate文档中推荐的工具类,Person.java , Test.java 测试用的类.都在test.hibe

从 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 }

Person:

01 package test.hibernate;
02
03 import java.util.LinkedList;
04 import java.util.List;
05
06 /**
07  *
08  */
09
10 @SuppressWarnings("serial")
11 public class Person implements java.io.Serializable {
12
13  // Fields
14
15  private Integer id;
16
17  private String name;
18
19  private String sex;
20
21  private Integer age;
22
23  private List list = new LinkedList();
24
25  // Collection accessors
26
27  public List getList() {
28   return list;
29  }
30
31  public void setList(List list) {
32   this.list = list;
33  }
34
35  /** default constrUCtor */
36  public Person() {
37  }
38
39  /** constructor with id */
40  public Person(Integer id) {
41   this.id = id;
42  }
43
44  // Property accessors
45
46  public Integer getId() {
47   return this.id;
48  }
49
50  public void setId(Integer id) {
51   this.id = id;
52  }
53
54  public String getName() {
55   return this.name;
56  }
57
58  public void setName(String name) {
59   this.name = name;
60  }
61
62  public String getSex() {
63   return this.sex;
64  }
65
66  public void setSex(String sex) {
67   this.sex = sex;
68  }
69
70  public Integer getAge() {
71   return this.age;
72  }
73
74  public void setAge(Integer age) {
75   this.age = age;
76  }
77
78 }


Tags:Hibernate Annotations 实战

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接