借助JDK 5.0的新特性Annotations,你可以使用它代替先前使用的XDoclet,不过当且仅当使用JDK 5.0的时候,为了保持向下兼容,用XDoclet生成mapping files仍然是最好的选择。
首先建立环境,将hibernate-annotations.jar和lib/ejb-3.0-edr2.jar复制到你的CLASSPATH下。
官方的建议是将Hibernate初始化放在static块内,建立如下的HibernateUtils类以方便使用。
package hello;import org.hibernate.*;import org.hibernate.cfg.*;import test.*;import test.animals.Dog;public class HibernateUtil {private static final SessionFactory sessionFactory; static { try { sessionFactory = new AnnotationConfiguration() .addPackage("test") .addAnnotatedClass(Flight.class) .addAnnotatedClass(Sky.class) .addAnnotatedClass(Person.class) .addAnnotatedClass(Dog.class) .buildSessionFactory(); } catch (Throwable ex) { // Log exception! throw new ExceptionInInitializerError(ex); } } public static Session getSession() throws HibernateException { return sessionFactory.openSession(); }}
这里有趣的地方就是使用AnnotationConfiguration并且声明包名和用于持久化的类名。当然你也可以在xml配置文件中加入。
这是一个不错的选择,你可以将hbm文件和annotation影射混合使用。还有一个问题就是子类不能在父类之前被配置,看下面的例子: cfg.addAnnotatedClass(Animal.class); cfg.addAnnotatedClass(Dog.class); // OK cfg.addAnnotatedClass(Dog.class); cfg.addAnnotatedClass(Animal.class); // AnnotationException!
这里Dog是Animal的子类。
(未完待续)
|