全面讲解Hibernate Annotations

Hibernate还是比较常用的,于是我研究了一下Hibernate Annotations,在这里拿出来和大家分享一下,希望对大家有用。

我们看看利用 Hibernate Annotations 如何做,只要三个类 不再需要 hbm.xml配置文件:

还要把用到的两个jar文件 放入的类路径中. 具体如何做,请参考  Hibernate Annotations 中文文档.HibernateUtil.java 也就是 Hibernate文档中推荐的工具类,Person.java 一个持久化的类, Test.java 测试用的类.都在test.hibernate.annotation 包中. 每个类的代码如下:

 
 
 
  1. package test.hibernate.annotation;  
  2.  
  3. import org.hibernate.HibernateException;  
  4. import org.hibernate.Session;  
  5. import org.hibernate.SessionFactory;  
  6. import org.hibernate.cfg.AnnotationConfiguration;  
  7. import org.hibernate.cfg.Configuration;  
  8.  
  9. public class HibernateUtil {  
  10. public static final SessionFactory sessionFactory;  
  11.  
  12. static {  
  13. try {  
  14. sessionFactory = new AnnotationConfiguration()     
  15. //注意: 建立 SessionFactory于前面的不同  
  16. .addPackage("test.hibernate.annotation")  
  17. .addAnnotatedClass(Person.class)  
  18.  
  19. .configure()  
  20. .buildSessionFactory();  
  21. //new Configuration().configure().buildSessionFactory();  
  22. }   
  23. catch (HibernateException e) {  
  24. // TODO Auto-generated catch block  
  25.  
  26. e.printStackTrace();  
  27. throw new ExceptionInInitializerError(e);  
  28. }  
  29. }  
  30.  
  31. public static final ThreadLocal<Session> session = new ThreadLocal<Session>();  
  32.  
  33. public static Session currentSession() throws HibernateException {  
  34. Session s = session.get();  
  35.  
  36. if(s == null) {  
  37. s = sessionFactory.openSession();  
  38. session.set(s);  
  39. }  
  40.  
  41. return s;  
  42. }  
  43.  
  44. public static void closeSession() throws HibernateException {  
  45. Session s = session.get();  
  46. if(s != null) {  
  47. s.close();  
  48. }  
  49. session.set(null);  
  50. }  

不需要了 hbm.xml 映射文件, 是不是简单了一些 .给人认为简化了一些不是主要目的.主要是可以了解一下 EJB3 的持久化机制,提高一下开发效率才是重要的.

好了.Hibernate Annotations的例子就完了

【编辑推荐】

  1. Hibernate创建和持久化Product
  2. 浅谈Hibernate工作方式
  3. 浅谈Hibernate OrderItem
  4. 简述Hibernate历史背景
  5. Hibernate的Orders OrderItem类
THE END