jpa 表注释和字段注释
JPA annotations are used in mapping java objects to the database tables, columns etc. Hibernate is the most popular implement of JPA specification and provides some additional annotations. Today we will look into JPA annotations as well as Hibernate annotations with brief code snippets.
JPA批注用于将Java对象映射到数据库表,列等。Hibernate是JPA规范中最流行的实现,并提供了一些其他批注。 今天,我们将研究带有简短代码段的JPA注释以及Hibernate注释。
JPA注释–Hibernate注释 (JPA Annotations – Hibernate Annotations)
Java annotation is a form of metadata that can be added to Java source code. Java annotations can be read from source files. It can also be embedded in and read from class files generated by the compiler. This allows annotations to be retained by JVM at run-time.
Java批注是一种可以添加到Java源代码中的元数据。 可以从源文件中读取Java注释。 它也可以嵌入到编译器生成的类文件中并从中读取。 这允许注释在运行时由JVM保留。
JPA annotations are not part of standard JDK, so you will get it when you add any implementation framework. For example, below hibernate maven dependency will get you JPA annotations too.
JPA批注不是标准JDK的一部分,因此在添加任何实现框架时都将获得它。 例如,在HibernateMaven依赖项下面也会为您提供JPA批注。
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
用于将Java对象映射到数据库表的JPA注释 (JPA Annotations for mapping java object to database table)
Let us look at some of the important JPA annotations. Note that these annotations are present in javax.persistence
package.
让我们看一些重要的JPA批注。 请注意,这些注释存在于javax.persistence
包中。
javax.persistence.Entity
: Specifies that the class is an entity. This annotation can be applied on Class, Interface of Enums.import javax.persistence.Entity; @Entity public class Employee implements Serializable { }
javax.persistence.Entity
:指定该类是一个实体。 该注释可以应用于“类”,“枚举接口”。@Table
: It specifies the table in the database with which this entity is mapped. In the example below the data will be stores in the “employee” table. Name attribute of @Table annotation is used to specify the table name.import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "employee") public class Employee implements Serializable { }
@Table
:它指定数据库中与该实体映射的表。 在下面的示例中,数据将存储在“员工”表中。 @Table批注的Name属性用于指定表名。@Column
: Specify the column mapping using @Column annotation. Name attribute of this annotation is used for specifying the table’s column name.import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "employee") public class Employee implements Serializable { @Column(name = "employee_name") private String employeeName; }
@Column
:使用@Column批注指定列映射。 此批注的Name属性用于指定表的列名。@Id
: This annotation specifies the primary key of the entity.import javax.persistence.*; @Entity @Table(name = "employee") public class Employee implements Serializable { @Id @Column(name = "id") private int id; }
@Id
:此注释指定实体的主键。@GeneratedValue
: This annotation specifies the generation strategies for the values of primary keys.import javax.persistence.*; @Entity @Table(name = "employee") public class Employee implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy=SEQUENCE, generator="ID_SEQ") private int id; }
@GeneratedValue
:此批注指定主键值的生成策略。@Version
: We can control versioning or concurrency using this annotation.import javax.persistence.*; @Entity @Table(name = "employee") public class Employee implements Serializable { @Version @Column(name = "version") private Date version; }
@Version
:我们可以使用此注释来控制版本控制或并发。@OrderBy
: Sort your data using @OrderBy annotation. In example below, it will sort all employees_address by their id in ascending order.@OrderBy("id asc") private Set employee_address;
@OrderBy
:使用@OrderBy批注对数据进行排序。 在下面的示例中,它将按其ID升序对所有employee_address进行排序。@Transient
: Every non static and non-transient property of an entity is considered persistent, unless you annotate it as @Transient.@Transient Private int employeePhone;
@Transient
:实体的每个非静态和非瞬态属性都被视为持久属性,除非您将其注释为@Transient。@Lob
: Large objects are declared with @Lob.@Lob public String getEmployeeAddress() { return employeeAddress; }
@Lob
:大对象用@Lob声明。
The above set of annotation are most commonly used JPA annotations to define an entity.
上面的批注是最常用的JPA批注,用于定义实体。
表之间映射的Hibernate注释 (Hibernate Annotations for Mapping between tables)
We have another set of annotations that are used to specify the association mapping between different tables and entities.
我们还有另一组注释,用于指定不同表和实体之间的关联映射。
We will take an example considering the below mentioned scenario.
我们将考虑下面提到的情况作为示例。
- Tables ’employee’ and ’employeeDetail’ have one-to-one association and they share the same primary key. 表“ employee”和“ employeeDetail”具有一对一关联,并且它们共享相同的主键。
- Tables ‘communication’ and ‘communicationDetail’ are linked by a foreign key. It is also a one to one association. 表“ communication”和“ communicationDetail”通过外键链接。 这也是一对一的关联。
- Tables ‘communication’ and ’employee’ are linked using a foreign key in many-to-one association with communication being the owner. 表“ communication”和“ employee”是使用外键在多对一关联中链接在一起的,并且通信是所有者。
- Tables ’employee’ and ’employeeStatus’ are linked through a foreign key in many-to-one association with employee being the owner. 表“ employee”和“ employeeStatus”通过多对一关联关系中的外键链接,而雇员为所有者。
@OneToOne
Employee and EmployeeDetail entities share the same primary key and we can associate them using @OneToOne and @PrimaryKeyJoinColumn.
In this case the id property of EmployeeDetail is not annotated with @GeneratedValue. The id value of Employee will be used for used for id of EmployeeDetail.
@OneToOne
Employee和EmployeeDetail实体共享相同的主键,我们可以使用@OneToOne和@PrimaryKeyJoinColumn将它们关联。
在这种情况下,EmployeeDetail的id属性未使用@GeneratedValue进行注释。 Employee的id值将用于EmployeeDetail的id。
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToOne(cascade = CascadeType.MERGE)
@PrimaryKeyJoinColumn
private EmployeeDetail employeeDetail;
}
@Entity
@Table(name = "employeeDetail")
public class EmployeeDetail implements Serializable {
@Id
@Column(name = "id")
private int id;
}
Points to note:
注意事项:
- @PrimaryKeyJoinColumn should be used for associated entities sharing the same primary key. @PrimaryKeyJoinColumn应该用于共享相同主键的关联实体。
- @JoinColumn & @OneToOne should be mappedBy attribute when foreign key is held by one of the entities. 当外键由实体之一持有时,应将@JoinColumn和@OneToOne映射为属性。
Communication and CommunicationDetail are linked through a foreign key, so @OneToOne and @JoinColumn annotations can be used. In snippet mentioned below, the id genereated for Communication will be mapped to ‘communication_id’ column of CommunicationDetail table. @MapsId is used for the same.
Communication和CommunicationDetail通过外键链接,因此可以使用@OneToOne和@JoinColumn批注。 在下面提到的代码段中,为Communication生成的id将映射到CommunicationDetail表的'communication_id'列。 @MapsId用于相同。
@Entity
@Table(name = "communicationDetail")
public class CommunicationDetail implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToOne
@MapsId
@JoinColumn(name = "communicationId")
private Communication communication;
}
@Entity
@Table(name = "communication")
public class Communication implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue
private Integer id;
@OneToOne(mappedBy = "communication", cascade = CascadeType.ALL)
private CommunicationDetail communicationDetail;
}
@ManyToOne
Many employees can share the same status. So, employee to employeeStatus is a many to one relation. @ManyToOne annotation can be used for the same.
@ManyToOne
许多员工可以拥有相同的身份。 因此,员工与employeeStatus是一对多的关系。 @ManyToOne批注可用于相同的注释。
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@ManyToOne
@JoinColumn(name = "statusId")
private EmployeeStatus status;
}
@OneToMany
Employee to Communication will be a one-to-many relationship. The owner of this relationship is Communication so, we will use ‘mappedBy’ attribute in Employee to make it bi-directional relationship.
@OneToMany
员工之间的沟通将是一对多的关系。 该关系的所有者是Communication,因此,我们将在Employee中使用'mappedBy'属性使其成为双向关系。
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
@OrderBy("firstName asc")
private Set communications;
}
@PrimaryKeyJoinColumn
This annotation is used to associate entities sharing the same primary key.
@PrimaryKeyJoinColumn
该注释用于关联共享相同主键的实体。
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToOne(cascade = CascadeType.MERGE)
@PrimaryKeyJoinColumn
private EmployeeDetail employeeDetail;
}
@JoinColumn
@JoinColumn annotation is used for one-to-one or many-to-one associations when foreign key is held by one of the entities.
@JoinColumn
当外键由实体之一持有时,@ JoinColumn批注用于一对一或多对一关联。
@ManyToOne
@JoinColumn(name = "statusId")
private EmployeeStatus status;
@JoinTable
: @JoinTable and mappedBy should be used for entities linked through an association table.
@JoinTable
:@JoinTable和mappedBy应该用于通过关联表链接的实体。
@MapsId
: Two entities with shared key can be persisted using @MapsId annotation.
@MapsId
:可以使用@MapsId注释保留具有共享密钥的两个实体。
@OneToOne
@MapsId
@JoinColumn(name = "communicationId")
private Communication communication;
用于继承映射的Hibernate注释 (Hibernate Annotations for inheritance mapping)
Now let us try to understand the inheritance mapping annotation in Hibernate.
现在让我们尝试了解Hibernate中的继承映射注释。
Hibernate supports the three basic inheritance mapping strategies:
Hibernate支持三种基本的继承映射策略:
- table per class hierarchy 每个类层次结构的表
- table per subclass 每个子类表
- table per concrete class 每个具体类别的表格
we will consider example for each type.
我们将考虑每种类型的示例。
- Table per class hierarchy – single table per Class Hierarchy Strategy.
每个类层次结构的表–每个类层次结构策略的单个表。@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING ) @DiscriminatorValue("Car") public class Car { } @Entity @DiscriminatorValue("BMW") public class BMW extends Car { }
- Table per class/subclass – joined subclass Strategy.
每个类/子类的表–联接子类策略。@Entity @Inheritance(strategy=InheritanceType.JOINED) public class Ship implements Serializable {} @Entity @PrimaryKeyJoinColumn public class Titanic extends Ship {}
- Table per concrete class.
每个具体类的表。@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Aeroplane implements Serializable {}
- @DiscriminatorColumn: As the name suggests this column is the descriminator and this annotation specifies the discriminator column for the SINGLE_TABLE and JOINED Inheritance mapping strategies.
@DiscriminatorColumn:顾名思义,此列为描述符,此注释为SINGLE_TABLE和JOINED继承映射策略指定了discriminator列。@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING )
That’s all for JPA and Hibernate annotations.
JPA和Hibernate注释就这些了。
Reference: JSR 338, Hibernate API Docs
参考: JSR 338 , Hibernate API文档
翻译自: https://www.journaldev.com/17803/jpa-hibernate-annotations
jpa 表注释和字段注释