熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Hibernate Annotations 實戰介紹

2022-06-13   來源: Java開源技術 
從 hbmxml 到 Annotations

  下面讓我們先看一個通常用 hbmxml 映射文件的例子個類 HibernateUtiljava 也就是 Hibernate文檔中推薦的工具類Personjava  Testjava 測試用的類都在testhibernate 包中 每個類的代碼如下:

  HibernateUtil:

   package testhibernate;

import orghibernateHibernateException;
import orghibernateSession;
import orghibernateSessionFactory;
import orghibernatecfgConfiguration;

public class HibernateUtil {
   public static final SessionFactory sessionFactory;
  
   static {
     try {
       sessionFactory = new Configuration()
              nfigure()
               buildSessionFactory();
     } catch (HibernateException e) {
       // TODO Autogenerated catch block
      
       eprintStackTrace();
       throw new ExceptionInInitializerError(e);
     }
   }
  
   public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
  
   public static Session currentSession() throws HibernateException {
     Session s = sessionget();
    
     if(s == null) {
       s = sessionFactoryopenSession();
       sessionset(s);
     }
    
     return s;
   }
  
   public static void closeSession() throws HibernateException {
     Session s = sessionget();
     if(s != null) {
       sclose();
     }
     sessionset(null);
   }
}

  Person:

   package testhibernate;

import javautilLinkedList;
import javautilList;

/**
  *
  */

@SuppressWarnings(serial)
public class Person implements javaioSerializable {

   // 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) {
     thislist = list;
   }

   /** default constructor */
   public Person() {
   }

   /** constructor with id */
   public Person(Integer id) {
     thisid = id;
   }

   // Property accessors

   public Integer getId() {
     return thisid;
   }

   public void setId(Integer id) {
     thisid = id;
   }

   public String getName() {
     return thisname;
   }

   public void setName(String name) {
     thisname = name;
   }

   public String getSex() {
     return thissex;
   }

   public void setSex(String sex) {
     thissex = sex;
   }

   public Integer getAge() {
     return thisage;
   }

   public void setAge(Integer age) {
     thisage = age;
   }

}

  Test:

   /*
  * Created on
  * @author
  */
package testhibernate;

import javasqlSQLException;

import orghibernateFlushMode;
import orghibernateHibernateException;
import orghibernateSession;
import orghibernateTransaction;

public class Test {
  
   public static void main(String [] args) {
     Session s = HibernateUtilcurrentSession();
    
     Transaction tx = sbeginTransaction();   
    
//    Person p = (Person) sload(Personclass );
//    Systemoutprintln(pgetName());
     Person p = new Person();
    
     psetAge();
     psetName(icerain);
     psetSex(male);
     ssave(p);
     sflush();
     /*
     Person p = (Person) sget(Personclass new Integer());
     Systemoutprintln(pgetName());
     psetName(ice);
     ssaveOrUpdate(p);
     sflush();
     Person p = (Person) sget(Personclass new Integer());
     Systemoutprintln(pgetName());
     sdelete(p);
     */
    
     mit(); 
     try {
       Systemoutprintln(pgetName());
     } catch (Exception e) {
       // TODO Autogenerated catch block
       eprintStackTrace();
     }
    
     HibernateUtilcloseSession();
   }
}

  hibernatecfgxml 配置文件如下利用mysql 數據庫

  <?xml version= encoding=UTF?>

  <hibernateconfiguration>

  <sessionfactory>

  <property name=nnectiondriver_class>orggjtmmmysqlDriver</property>

  <property name=nnectionpassword>你的數據庫密碼</property>

  <property name=nnectionurl>jdbc:mysql://localhost/數據庫名</property>

  <property name=nnectionusername>用戶名</property>

  <property name=hibernatedialect>orghibernatedialectMySQLDialect</property>

  <property name=show_sql>true</property>

  <property name=hibernatetransactionfactory_class>orghibernatetransactionJDBCTransactionFactory</property>

  <property name=hibernatetransactionauto_close_session>false</property>

  <property name=hibernatehbmddlauto>update</property>

  <mapping resource=test/hibernate/annotation/Personhbmxml/>

  </sessionfactory>

  </hibernateconfiguration>

  其中 配置了<property name=hibernatehbmddlauto>update</property>屬性 自動導入數據庫ddl生產的ddl sql語句如下

  create table person (id integer not null auto_increment name varchar() sex varchar() age integer person integer primary key (id))

  alter table person add index FKCEBCAC (person) add constraint FKCEBCAC foreign key (person) references person (id)

  而Personhbmxml 文件如下:

  <?xml version=?>

  <hibernatemapping>

  <class name=testhibernatePerson 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>

  <onetomany class=testhibernatePerson/>

  </bag>

  </class>

  </hibernatemapping>

  下面讓我們看看利用 Hibernate Annotations 如何做只要三個類 不再需要 hbmxml配置文件:

  還要把用到的兩個jar文件 放入的類路徑中 具體如何做請參考  Hibernate Annotations 中文文檔

  HibernateUtiljava 也就是 Hibernate文檔中推薦的工具類Personjava 一個持久化的類 Testjava 測試用的類都在testhibernateannotation 包中 每個類的代碼如下:

  HibernateUtil

   package testhibernateannotation;

import orghibernateHibernateException;
import orghibernateSession;
import orghibernateSessionFactory;
import orghibernatecfgAnnotationConfiguration;
import orghibernatecfgConfiguration;

public class HibernateUtil {
   public static final SessionFactory sessionFactory;
  
   static {
     try {
       sessionFactory = new AnnotationConfiguration()   //注意: 建立 SessionFactory於前面的不同
                 addPackage(testhibernateannotation)
                 addAnnotatedClass(Personclass)
                
                nfigure()
                 buildSessionFactory();
         //new Configuration(nfigure()buildSessionFactory();
     } catch (HibernateException e) {
       // TODO Autogenerated catch block
      
       eprintStackTrace();
       throw new ExceptionInInitializerError(e);
     }
   }
  
   public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
  
   public static Session currentSession() throws HibernateException {
     Session s = sessionget();
    
     if(s == null) {
       s = sessionFactoryopenSession();
       sessionset(s);
     }
    
     return s;
   }
  
   public static void closeSession() throws HibernateException {
     Session s = sessionget();
     if(s != null) {
       sclose();
     }
     sessionset(null);
   }
}

  Person:

   package testhibernateannotation;

import javautilLinkedList;
import javautilList;

import javaxpersistenceAccessType;
import javaxpersistenceBasic;
import javaxpersistenceEntity;
import javaxpersistenceGeneratorType;
import javaxpersistenceId;
import javaxpersistenceOneToMany;
import javaxpersistenceTable;
import javaxpersistenceTransient;

/**
  *
  */

@SuppressWarnings(serial)
@Entity(access = AccessTypePROPERTY) //定義該類為實體類
@Table   //映射表
public class Person implements javaioSerializable {

   // 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) {
     thisid = id;
   }

   // Property accessors
   @Id
   public Integer getId() {
     return thisid;
   }

   public void setId(Integer id) {
     thisid = id;
   }

   @Basic
   public String getName() {
     return thisname;
   }

   public void setName(String name) {
     thisname = name;
   }

   @Basic
   public String getSex() {
     return thissex;
   }

   public void setSex(String sex) {
     thissex = sex;
   }

   @Basic
   public Integer getAge() {
     return thisage;
   }

   public void setAge(Integer age) {
     thisage = age;
   }
   @Transient  //由於本例不打算演示集合映射 所有聲明該屬性為 Transient
   public List getList() {
     return list;
   }

   public void setList(List list) {
     thislist = list;
   }

}

  注意該實體類中的屬性都使用了默認值

  Testjava 代碼同上

  不需要了 hbmxml 映射文件 是不是簡單了一些 給人認為簡化了一些不是主要目的主要是可以了解一下 EJB 的持久化機制 提高一下開發效率才是重要的

  好了 本例就完了 感覺怎麼樣了 歡迎你來批批

  PS:

  生成的數據庫表 和 程序執行後的 數據庫情況如下

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

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

  


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28051.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.