e="test.hibernate.Person" table="person">
<id name="id" type="integer">
<column name="id" />
<generator class="native"></generator>
</id>
<property name="name" type="string">
<column name="name" />
</property>
<property name="sex" type="string">
<column name="sex" />
</property>
<property name="age" type="integer">
<column name="age" />
</property>
<bag name="list" cascade="all">
<key column="person"></key>
<one-to-many class="test.hibernate.Person"/>
</bag>
</class>
</hibernate-mapping>
下面让我们看看利用 Hibernate Annotations 如何做,只要三个类 不再需要 hbm.xml配置文件:
还要把用到的两个jar文件 放入的类路径中. 具体如何做,请参考 Hibernate Annotations 中文文档
http://hibernate.6644.net
HibernateUtil.java 也就是 Hibernate文档中推荐的工具类,Person.java 一个持久化的类, Test.java 测试用的类.都在test.hibernate.annotation 包中. 每个类的代码如下:
HibernateUtil
01 package test.hibernate.annotation;
02
03 import org.hibernate.HibernateException;
04 import org.hibernate.Session;
05 import org.hibernate.SessionFactory;
06 import org.hibernate.cfg.AnnotationConfiguration;
07 import org.hibernate.cfg.Configuration;
08
09 public class HibernateUtil {
10 public static final SessionFactory sessionFactory;
11
12 static {
13 try {
14 sessionFactory = new AnnotationConfiguration() //注意: 建立 SessionFactory于前面的不同
15 .addPackage("test.hibernate.annotation")
16 .addAnnotatedClass(Person.class)
17
18 .configure()
19 .buildSessionFactory();
20 //new Configuration().configure().buildSessionFactory();
21 } catch (HibernateException e) {
22 // TODO Auto-generated catch block
23
24 e.printStackTrace();
25 throw new ExceptionInInitializerError(e);
26 }
27 }
28
29 public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
30
31 public static Session currentSession() throws HibernateException {
32 Session s = session.get();
33
34 if(s == null) {
35 s = sessionFactory.openSession();
36 session.set(s);
37 }
38
39 return s;
40 }
41
42 public static void closeSession() throws HibernateException {
43 Session s = session.get();
44 if(s != null) {
45 s.close();
46 }
47 session.set(null);
48 }
49 }
Hibernate Annotations实战--从hbm.xml到Annotations(5)
时间:2011-07-28
Person:
01 package test.hibernate.annotation;
02
03 import java.util.LinkedList;
04 import java.util.List;
05
06 import javax.persistence.AccessType;
07 import javax.persistence.Basic;
08 import javax.persistence.Entity;
09 import javax.persistence.GeneratorType;
10 import
|