鍍金池/ 教程/ Java/ 注釋
例子
注釋
映射類型
ORM 概覽
環(huán)境
標(biāo)準(zhǔn)查詢
原生 SQL
持久化類
查詢語(yǔ)言
配置
批處理
緩存
架構(gòu)
會(huì)話
映射文件
O/R 映射
簡(jiǎn)介
攔截器

注釋

到現(xiàn)在為止,你已經(jīng)看到 Hibernate 如何使用 XML 映射文件來(lái)完成從 POJO 到數(shù)據(jù)庫(kù)表的數(shù)據(jù)轉(zhuǎn)換的,反之亦然。Hibernate 注釋是無(wú)需使用 XML 文件來(lái)定義映射的最新方法。你可以額外使用注釋或直接代替 XML 映射元數(shù)據(jù)。

Hibernate 注釋是一種強(qiáng)大的來(lái)給對(duì)象和關(guān)系映射表提供元數(shù)據(jù)的方法。所有的元數(shù)據(jù)被添加到 POJO java 文件代碼中,這有利于用戶在開(kāi)發(fā)時(shí)更好的理解表的結(jié)構(gòu)和 POJO。

如果你想讓你的應(yīng)用程序移植到其它 EJB 3 的 ORM 應(yīng)用程序中,您必須使用注釋來(lái)表示映射信息,但是如果想要得到更大的靈活性,那么你應(yīng)該使用基于 XML 的映射。

Hibernate 注釋的環(huán)境設(shè)置

首先你必須確定你使用的是 JDK 5.0,否則你需要升級(jí)你的 JDK 至 JDK 5.0,來(lái)使你的主機(jī)能夠支持注釋。

其次,你需要安裝 Hibernate 3.x 注釋包,可以從 sourceforge 行下載:下載 Hibernate 注釋 并且從 Hibernate 注釋發(fā)布中拷貝 hibernate-annotations.jar, lib/hibernate-comons-annotations.jarlib/ejb3-persistence.jar 到你的 CLASSPATH。

注釋類示例

正如我上面所提到的,所有的元數(shù)據(jù)被添加到 POJO java 文件代碼中,這有利于用戶在開(kāi)發(fā)時(shí)更好的理解表的結(jié)構(gòu)和 POJO。

下面我們將使用 EMPLOYEE 表來(lái)存儲(chǔ)對(duì)象:

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

以下是用帶有注釋的 Employee 類來(lái)映射使用定義好的 Employee 表的對(duì)象:

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
   @Id @GeneratedValue
   @Column(name = "id")
   private int id;

   @Column(name = "first_name")
   private String firstName;

   @Column(name = "last_name")
   private String lastName;

   @Column(name = "salary")
   private int salary;  

   public Employee() {}
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

Hibernate 檢測(cè)到 @Id 注釋字段并且認(rèn)定它應(yīng)該在運(yùn)行時(shí)通過(guò)字段直接訪問(wèn)一個(gè)對(duì)象上的屬性。如果你將 @Id 注釋放在 getId() 方法中,你可以通過(guò)默認(rèn)的 getter 和 setter 方法來(lái)訪問(wèn)屬性。因此,所有其它注釋也放在字段或是 getter 方法中,決定于選擇的策略。下一節(jié)將解釋上面的類中使用的注釋。

@Entity 注釋

EJB 3 標(biāo)準(zhǔn)的注釋包含在 javax.persistence 包,所以我們第一步需要導(dǎo)入這個(gè)包。第二步我們對(duì) Employee 類使用 @Entity 注釋,標(biāo)志著這個(gè)類為一個(gè)實(shí)體 bean,所以它必須含有一個(gè)沒(méi)有參數(shù)的構(gòu)造函數(shù)并且在可保護(hù)范圍是可見(jiàn)的。

@Table 注釋

@table 注釋允許您明確表的詳細(xì)信息保證實(shí)體在數(shù)據(jù)庫(kù)中持續(xù)存在。

@table 注釋提供了四個(gè)屬性,允許您覆蓋的表的名稱,目錄及其模式,在表中可以對(duì)列制定獨(dú)特的約束?,F(xiàn)在我們使用的是表名為 EMPLOYEE。

@Id 和 @GeneratedValue 注釋

每一個(gè)實(shí)體 bean 都有一個(gè)主鍵,你在類中可以用 @Id 來(lái)進(jìn)行注釋。主鍵可以是一個(gè)字段或者是多個(gè)字段的組合,這取決于你的表的結(jié)構(gòu)。

默認(rèn)情況下,@Id 注釋將自動(dòng)確定最合適的主鍵生成策略,但是你可以通過(guò)使用 @GeneratedValue 注釋來(lái)覆蓋掉它。strategygenerator 這兩個(gè)參數(shù)我不打算在這里討論,所以我們只使用默認(rèn)鍵生成策略。讓 Hibernate 確定使用哪些生成器類型來(lái)使代碼移植于不同的數(shù)據(jù)庫(kù)之間。

@Column Annotation

@Column 注釋用于指定某一列與某一個(gè)字段或是屬性映射的細(xì)節(jié)信息。您可以使用下列注釋的最常用的屬性:

  • name 屬性允許顯式地指定列的名稱。
  • length 屬性為用于映射一個(gè)值,特別為一個(gè)字符串值的列的大小。
  • nullable 屬性允許當(dāng)生成模式時(shí),一個(gè)列可以被標(biāo)記為非空。
  • unique 屬性允許列中只能含有唯一的內(nèi)容

創(chuàng)建應(yīng)用類

最后,我們將創(chuàng)建應(yīng)用程序類,并使用 main() 方法來(lái)運(yùn)行應(yīng)用程序。我們將使用此應(yīng)用程序來(lái)保存一些員工的記錄,然后我們對(duì)這些記錄進(jìn)行 CRUD 操作。

import java.util.List; 
import java.util.Date;
import java.util.Iterator; 

import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try{
         factory = new AnnotationConfiguration().
                   configure().
                   //addPackage("com.xyz") //add package if used.
                   addAnnotatedClass(Employee.class).
                   buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee();
         employee.setFirstName(fname);
         employee.setLastName(lname);
         employee.setSalary(salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = 
                           employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to UPDATE salary for an employee */
   public void updateEmployee(Integer EmployeeID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                    (Employee)session.get(Employee.class, EmployeeID); 
         employee.setSalary( salary );
         session.update(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to DELETE an employee from the records */
   public void deleteEmployee(Integer EmployeeID){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                   (Employee)session.get(Employee.class, EmployeeID); 
         session.delete(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
}

數(shù)據(jù)庫(kù)配置

現(xiàn)在,讓我們創(chuàng)建 hibernate.cfg.xml 配置文件來(lái)定義數(shù)據(jù)庫(kù)相關(guān)參數(shù)。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <property name="hibernate.dialect">
      org.hibernate.dialect.MySQLDialect
   </property>
   <property name="hibernate.connection.driver_class">
      com.mysql.jdbc.Driver
   </property>

   <!-- Assume students is the database name -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/test
   </property>
   <property name="hibernate.connection.username">
      root
   </property>
   <property name="hibernate.connection.password">
      cohondob
   </property>

</session-factory>
</hibernate-configuration>

編譯和執(zhí)行

這里是編譯并運(yùn)行以上提到的應(yīng)用程序的步驟。再繼續(xù)編譯和運(yùn)行之前需要確保你正確設(shè)置路徑和類路徑。

  • 從目錄中刪除 Employee.hbm.xml 映射文件。
  • 創(chuàng)建上述 Employee.java 源文件并編譯。
  • 創(chuàng)建上述 ManageEmployee.java 源文件并編譯。
  • 執(zhí)行 ManageEmployee 二進(jìn)制程序。

你將得到如下結(jié)果,并且會(huì)在 EMPLOYEE 表中記錄。

$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

First Name: Zara  Last Name: Ali  Salary: 1000
First Name: Daisy  Last Name: Das  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000

如果你查看 EMPLOYEE 表,它將有如下記錄:

mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 29 | Zara       | Ali       |   5000 |
| 31 | John       | Paul      |  10000 |
+----+------------+-----------+--------+
2 rows in set (0.00 sec

mysql>
上一篇:持久化類下一篇:架構(gòu)