全面講解Hibernate Annotations
我們看看利用 Hibernate Annotations 如何做,只要三個類 不再需要 hbm.xml配置文件:
還要把用到的兩個jar文件 放入的類路徑中. 具體如何做,請參考 Hibernate Annotations 中文文檔.HibernateUtil.java 也就是 Hibernate文檔中推薦的工具類,Person.java 一個持久化的類, Test.java 測試用的類.都在test.hibernate.annotation 包中. 每個類的代碼如下:
- package test.hibernate.annotation;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.AnnotationConfiguration;
- import org.hibernate.cfg.Configuration;
- public class HibernateUtil {
- public static final SessionFactory sessionFactory;
- static {
- try {
- sessionFactory = new AnnotationConfiguration()
- //注意: 建立 SessionFactory于前面的不同
- .addPackage("test.hibernate.annotation")
- .addAnnotatedClass(Person.class)
- .configure()
- .buildSessionFactory();
- //new Configuration().configure().buildSessionFactory();
- }
- catch (HibernateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- throw new ExceptionInInitializerError(e);
- }
- }
- public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
- public static Session currentSession() throws HibernateException {
- Session s = session.get();
- if(s == null) {
- s = sessionFactory.openSession();
- session.set(s);
- }
- return s;
- }
- public static void closeSession() throws HibernateException {
- Session s = session.get();
- if(s != null) {
- s.close();
- }
- session.set(null);
- }
- }
不需要了 hbm.xml 映射文件, 是不是簡單了一些 .給人認為簡化了一些不是主要目的.主要是可以了解一下 EJB3 的持久化機制,提高一下開發(fā)效率才是重要的.
好了.Hibernate Annotations的例子就完了
【編輯推薦】