全面讲解Hibernate Annotations

开发 后端
这里介绍Hibernate Annotations,HibernateUtil.java 也就是 Hibernate文档中推荐的工具类,Person.java 一个持久化的类。
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类
责任编辑:佚名 来源: IT168
相关推荐

2009-09-28 17:27:27

Hibernate A

2009-09-24 10:50:31

Hibernate主键

2009-09-23 15:50:21

Hibernate u

2009-09-27 16:01:04

Hibernate A

2009-09-24 11:04:56

Hibernate二级

2009-09-29 17:11:23

Hibernate T

2009-09-21 16:56:14

Hibernateibatis

2009-09-28 16:54:34

Hibernate示例

2009-09-28 13:49:44

Hibernate Q

2009-09-25 16:27:33

Hibernate S

2009-09-28 10:24:58

Hibernate基础

2009-09-25 09:46:03

Hibernate s

2009-09-23 17:41:05

Hibernate事务

2009-09-24 18:11:56

Hibernate q

2009-09-29 14:03:14

Hibernate数据

2009-09-25 16:08:12

Hibernate f

2009-09-28 11:30:53

Hibernate核心

2009-09-22 15:22:08

Hibernate性能

2009-09-22 11:24:07

Hibernate查询

2009-09-21 17:46:34

Hibernate持久
点赞
收藏

51CTO技术栈公众号