Hibernate 简明教程

Hibernate - Persistent Class

Hibernate 的整个概念是获取 Java 类属性中的值,并将它们持久化到数据库表中。映射文档帮助 Hibernate 确定如何从类中提取值,并将其与表和关联字段进行映射。

The entire concept of Hibernate is to take the values from Java class attributes and persist them to a database table. A mapping document helps Hibernate in determining how to pull the values from the classes and map them with table and associated fields.

在数据库表中存储其对象或实例的 Java 类在 Hibernate 中称为持久类。如果这些类遵循一些简单规则,Hibernate 就能很好地工作,这些规则也称为 Plain Old Java Object (POJO) 编程模型。

Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model.

以下为持久类的主要规则,但其中没有一项属于硬性要求:

There are following main rules of persistent classes, however, none of these rules are hard requirements −

  1. All Java classes that will be persisted need a default constructor.

  2. All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table.

  3. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.

  4. A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.

  5. All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.

POJO 名称用于强调给定对象是普通的 Java 对象,而不是特殊对象,特别是不是 Enterprise JavaBean。

The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean.

Simple POJO Example

基于以上提到的几个规则,我们可以如下定义一个 POJO 类:

Based on the few rules mentioned above, we can define a POJO class as follows −

public class Employee {
   private int id;
   private String firstName;
   private String lastName;
   private int salary;

   public Employee() {}
   public Employee(String fname, String lname, int salary) {
      this.firstName = fname;
      this.lastName = lname;
      this.salary = salary;
   }

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