Hibernate Annotations实战--从hbm.xml到Annotations
时间:2011-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 }
Hibernate Annotations实战--从hbm.xml到Annotations(2)
时间:2011-07-28
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 }
Hibernate Annotations实战--从hbm.xml到Annotations(3)
时间:2011-07-28
Test:
01 /*
02 * Created on
03 * @author
04 */
05 package test.hibe
|