Hibernate Annotations 实战(一)

来源:http://www.360doc.com/content/06/0425/12/5136_104878.shtml  

-- 从 hbm.xml 到 Annotations

任何获得Matrix授权的网站,转载请保留以下作者信息和链接:
作者:icess(作者的blog:http://blog.matrix.org.cn/page/icess)
关键字:Hibernate Validator

下面让我们先看一个通常用 hbm.xml 映射文件的例子. 有3个类 .HibernateUtil.java 也就是 Hibernate文档中推荐的工具类,Person.java 一个持久化的类, Test.java 测试用的类.都在test.hibernate 包中. 每个类的代码如下:

HIbernateUtil工具类:

 

 package test.hibernate;
 
 import org.hibernate.HibernateException;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.cfg.Configuration;
 
 public class HibernateUtil {
   public static final SessionFactory sessionFactory;
   
   static {
     try {
       sessionFactory = 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);
   }
 }
 

 

 

 用户实体类:Person 

 

 package test.hibernate;
 
 import java.util.LinkedList;
 import java.util.List;
 
 /**
  * 
  */
 
 @SuppressWarnings("serial")
 public class Person implements java.io.Serializable {
 
   // Fields
 
   private Integer id;
 
   private String name;
 
   private String sex;
 
   private Integer age;
 
   private List list = new LinkedList();
 
   // Collection accessors
 
   public List getList() {
     return list;
   }
 
   public void setList(List list) {
     this.list = list;
   }
 
   /** default constructor */
   public Person() {
   }
 
   /** constructor with id */
   public Person(Integer id) {
     this.id = id;
   }
 
   // Property accessors
 
   public Integer getId() {
     return this.id;
   }
 
   public void setId(Integer id) {
     this.id = id;
   }
 
   public String getName() {
     return this.name;
   }
 
   public void setName(String name) {
     this.name = name;
   }
 
   public String getSex() {
     return this.sex;
   }
 
   public void setSex(String sex) {
     this.sex = sex;
   }
 
   public Integer getAge() {
     return this.age;
   }
 
   public void setAge(Integer age) {
     this.age = age;
   }
 
 }
 

 

 

 

 

 /*
  * Created on 
  * @author 
  */
 package test.hibernate;
 
 import java.sql.SQLException;
 
 import org.hibernate.FlushMode;
 import org.hibernate.HibernateException;
 import org.hibernate.Session;
 import org.hibernate.Transaction;
 
 public class Test {
   
   public static void main(String [] args) {
     Session s = HibernateUtil.currentSession();
     
     Transaction tx = s.beginTransaction();    
     
 //    Person p = (Person) s.load(Person.class, 1);
 //    System.out.println(p.getName());
     Person p = new Person();
     
     p.setAge(19);
     p.setName("icerain");
     p.setSex("male");
     s.save(p);
     s.flush();
     /*
     Person p2 = (Person) s.get(Person.class, new Integer(1));
     System.out.println(p2.getName());
     p2.setName("ice..");
     s.saveOrUpdate(p2);
     s.flush();
     Person p3 = (Person) s.get(Person.class, new Integer(2));
     System.out.println(p3.getName());
     s.delete(p3);
     */
     
     tx.commit();  
     try {
       System.out.println(p.getName());
     } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     
     HibernateUtil.closeSession();
   }
 }
  hibernate.cfg.xml 配置文件如下,利用mysql 数据库.

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>

<property name="hibernate.connection.password">你的数据库密码</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost/数据库名</property>

<property name="hibernate.connection.username">用户名</property>

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="show_sql">true</property>

<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

<property name="hibernate.transaction.auto_close_session">false</property>

<property name="hibernate.hbm2ddl.auto">update</property>

 

<mapping resource="test/hibernate/annotation/Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

 其中 配置了<property name="hibernate.hbm2ddl.auto">update</property>属性 自动导入数据库ddl.生产的ddl sql语句如下

create table person (id integer not null auto_increment, name varchar(255), sex varchar(255), age integer, person integer, primary key (id))
alter table person add index FKC4E39B5511C4A5C2 (person), add constraint FKC4E39B5511C4A5C2 foreign key (person) references person (id)

 

而Person.hbm.xml 文件如下:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="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://hb.6644.netHibernateUtil.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);
   }
 }

 

 package test.hibernate.annotation;
 
 import java.util.LinkedList;
 import java.util.List;
 
 import javax.persistence.AccessType;
 import javax.persistence.Basic;
 import javax.persistence.Entity;
 import javax.persistence.GeneratorType;
 import javax.persistence.Id;
 import javax.persistence.OneToMany;
 import javax.persistence.Table;
 import javax.persistence.Transient;
 
 /**
  * 
  */
 
 @SuppressWarnings("serial")
 @Entity(access = AccessType.PROPERTY) //定义该类为实体类
 @Table   //映射表
 public class Person implements java.io.Serializable {
 
   // Fields
 
   private Integer id;
 
   private String name;
 
   private String sex;
 
   private Integer age;
 
   private List list = new LinkedList();
 
   // Constructors
   /** default constructor */
   public Person() {
   }
 
   /** constructor with id */
   public Person(Integer id) {
     this.id = id;
   }
 
   // Property accessors
   @Id
   public Integer getId() {
     return this.id;
   }
 
   public void setId(Integer id) {
     this.id = id;
   }
 
   @Basic
   public String getName() {
     return this.name;
   }
 
   public void setName(String name) {
     this.name = name;
   }
 
   @Basic
   public String getSex() {
     return this.sex;
   }
 
   public void setSex(String sex) {
     this.sex = sex;
   }
 
   @Basic
   public Integer getAge() {
     return this.age;
   }
 
   public void setAge(Integer age) {
     this.age = age;
   }
   @Transient  //由于本例不打算演示集合映射 所有声明该属性为 Transient  
   public List getList() {
     return list;
   }
 
   public void setList(List list) {
     this.list = list;
   }
 
 }

 注意该实体类中的属性都使用了默认值.Test.java 代码同上不需要了 hbm.xml 映射文件, 是不是简单了一些 .给人认为简化了一些不是主要目的.主要是可以了解一下 EJB3 的持久化机制 ,提高一下开发效率才是重要的.好了 .本例就完了 . 感觉怎么样了 .欢迎你来批批.PS:生成的数据库表 和 程序执行后的 数据库情况如下:

mysql> describe person;
+--------+--------------+------+-----+---------+----------------+
|  Field  | Type          | Null  | Key | Default |          Extra |
+--------+--------------+------+-----+---------+----------------+
| id        | int(11)       | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | YES  |     | NULL    |                |
| sex    | varchar(255) | YES  |     | NULL    |                |
| age    | int(11)      | YES  |     | NULL    |                |
| person | int(11)      | YES  | MUL | NULL    |                |
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

mysql> select * from person;
+----+---------+------+------+--------+
| id | name    |  sex |  age | person |
+----+---------+------+------+--------+
|  1 | icerain | male |   19 |   NULL |
+----+---------+------+------+--------+
1 row in set (0.03 sec)

你可能感兴趣的:(Annotations)