Hibernate annotations

Reprinted: https://www.w3cschool.cn/hibernate/zief1iev.html

Notes

So far, you've seen how Hibernate uses XML mapping files to convert data from POJOs to database tables and vice versa. Hibernate annotations are the latest way to define mappings without using XML files. You can map metadata using annotations in addition or directly instead of XML.

Hibernate annotations are a powerful way to provide metadata to object and relational mapping tables. All metadata is added to the POJO java file code, which helps users to better understand the table structure and POJOs during development.

If you want to port your application to other EJB 3 ORM applications, you must use annotations to represent mapping information, but if you want more flexibility, you should use XML-based mapping.

Environment settings for Hibernate annotations

First you have to make sure you are using JDK 5.0, otherwise you need to upgrade your JDK to JDK 5.0 to enable your host to support annotations.

Second, you need to install the Hibernate 3.x annotations package, which can be downloaded from the sourceforge line: ( download Hibernate annotations )  and copy  hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and  lib/ejb3- persistence.jar  to your CLASSPATH.

Annotation class example

As I mentioned above, all metadata is added to the POJO java file code, which helps users to better understand the table structure and POJOs during development.

Below we will use the EMPLOYEE table to store objects:

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)
);

The following is an annotated Employee class to map objects using the defined Employee table:

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 detects the @Id annotated field and decides that it should directly access a property on an object through the field at runtime. If you put the @Id annotation in the getId() method, you can access the property through the default getter and setter methods. Therefore, all other annotations are also placed in fields or getter methods, depending on the chosen strategy. The next section will explain the annotations used in the classes above.

@Entity annotation

The EJB 3 standard annotations are contained in the  javax.persistence  package, so we need to import this package first. In the second step we use the @Entity annotation on the Employee class to  mark this class as an entity bean, so it must have a constructor with no parameters and be visible in the protectable scope.

@Table annotation

The @table annotation allows you to specify the details of the table to ensure that the entity persists in the database.

The @table annotation provides four attributes that allow you to override the name of the table, the catalog and its schema, where unique constraints can be placed on the columns in the table. Now we are using a table named EMPLOYEE.

@Id and @GeneratedValue annotations

Every entity bean has a primary key, which you can annotate with  @Id in the class  . The primary key can be a field or a combination of fields, depending on the structure of your table.

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

@Column Annotation

@Column 注释用于指定某一列与某一个字段或是属性映射的细节信息。您可以使用下列注释的最常用的属性:

  • name 属性允许显式地指定列的名称。
  • length 属性为用于映射一个值,特别为一个字符串值的列的大小。
  • nullable 属性允许当生成模式时,一个列可以被标记为非空。
  • unique 属性允许列中只能含有唯一的内容

创建应用类

最后,我们将创建应用程序类,并使用 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>

编译和执行

这里是编译并运行以上提到的应用程序的步骤。再继续编译和运行之前需要确保你正确设置路径和类路径。

  • 从目录中删除 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>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519716&siteId=291194637