目录

Hibernate - 注释( Annotations)

到目前为止,您已经了解了Hibernate如何使用XML映射文件将数据从POJO转换为数据库表,反之亦然。 Hibernate注释是在不使用XML文件的情况下定义映射的最新方法。 除了XML映射元数据之外,您还可以使用注释或替代XML映射元数据。

Hibernate Annotations是为Object和Relational Table映射提供元数据的强大方法。 所有元数据都与代码一起分配到POJO java文件中,这有助于用户在开发过程中同时理解表结构和POJO。

如果要将应用程序移植到其他符合EJB 3的ORM应用程序,则必须使用注释来表示映射信息,但如果您需要更大的灵活性,则应该使用基于XML的映射。

Hibernate注释的环境设置

首先,您必须确保使用JDK 5.0,否则需要将JDK升级到JDK 5.0以利用对注释的本机支持。

其次,您需要安装Hibernate 3.x annotations分发包,可从sourceforge获得:( 下载Hibernate Annotation )并复制hibernate-annotations.jar, lib/hibernate-comons-annotations.jarlib/ejb3-persistence.jar从Hibernate Annotations发行版到你的CLASSPATH。

带注释的类示例

正如我在使用Hibernate Annotation时所提到的,所有元数据都与代码一起被分配到POJO java文件中,这有助于用户在开发过程中同时理解表结构和POJO。

考虑我们将使用以下EMPLOYEE表来存储我们的对象 -

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表将Employee类与注释映射到映射对象 -

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检测到@Id注释位于某个字段上,并假定它应该在运行时直接通过字段访问对象的属性。 如果将@Id注释放在getId()方法上,则默认情况下将通过getter和setter方法启用对属性的访问。 因此,所有其他注释也会根据所选策略放置在字段或getter方法上。

以下部分将解释上述类中使用的注释。

@Entity Annotation

EJB 3标准注释包含在javax.persistence包中,因此我们将此包作为第一步导入。 其次,我们将@Entity注释用于Employee类,它将此类标记为实体bean,因此它必须具有至少受保护范围可见的无参数构造函数。

@Table注释

@Table注释允许您指定将用于在数据库中保留实体的表的详细信息。

@Table注释提供了四个属性,允许您覆盖表的名称,目录及其架构,并对表中的列强制执行唯一约束。 目前,我们只使用表名,即EMPLOYEE。

@Id和@GeneratedValue Annotations

每个实体bean都有一个主键,您可以使用@Id注释在类上进行注释。 主键可以是单个字段,也可以是多个字段的组合,具体取决于您的表结构。

默认情况下,@ Id注释将自动确定要使用的最合适的主键生成策略,但您可以通过应用@GeneratedValue注释来覆盖它,这需要两个参数strategygenerator ,我不打算在这里讨论,所以让我们只使用默认密钥生成策略。 让Hibernate确定使用哪种生成器类型使您的代码可以在不同的数据库之间移植。

@Column Annotation

@Column注释用于指定字段或属性将映射到的列的详细信息。 您可以将列注释与以下最常用的属性一起使用 -

  • name属性允许显式指定列的名称。

  • length属性允许用于映射值的列的大小,特别是String值。

  • nullable属性允许在生成模式时将列标记为NOT NULL。

  • unique属性允许将列标记为仅包含唯一值。

创建应用程序类 (Create Application Class)

最后,我们将使用main()方法创建应用程序类来运行应用程序。 我们将使用此应用程序来保存很少的员工记录,然后我们将对这些记录应用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(); 
      }
   }
}

数据库配置

现在让我们创建hibernate.cfg.xml配置文件来定义数据库相关参数。

<?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>

编译和执行 (Compilation and Execution)

以下是编译和运行上述应用程序的步骤。 确保在进行编译和执行之前已适当地设置了PATH和CLASSPATH。

  • 从路径中删除Employee.hbm.xml映射文件。

  • 如上所示创建Employee.java源文件并进行编译。

  • 创建ManageEmployee.java源文件,如上所示并编译它。

  • 执行ManageEmployee二进制文件以运行该程序。

您将获得以下结果,并且将在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>
↑回到顶部↑
WIKI教程 @2018