What are the basic hibernate persistent annotations?
This page talks about Hibernate mapping with JPA (Java Persistence Annotations). JPA entities are plain POJOs.
Actually, they are Hibernate persistent entities. Their mappings are defined through JDK 5.0 annotations instead of hbm.xml
files. JPA annotations are in the javax.persistence.* package.
@Entity - Marking a POJO as persistent entity
Every persistent POJO class is an entity and is declared using the @Entity annotation at the class level as
shown below:
@Entity example code |
import javax.persistence.Entity;
@Entity
public class Employee implements Serializable {
@Id
private Long empId;
|
@Entity declares the class as an entity i.e. a persistent POJO class.
@Id - Marking primary key of an entity
@Id declares the identifier property of the given entity. The mapped column
for the primary key of the entity is assumed to be the primary key of the primary table.
@Table - Defining the table
@Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity
mapping. If no @Table is defined the default values are used: the unqualified class name of the entity.
|
@Entity
@Table(name="EMPLOYEES")
public class Employee implements Serializable {
...
}
|
The @Table element contains a schema and catalog attributes, if they need to be defined. You can also define
unique constraints to the table using the @UniqueConstraint annotation in conjunction with @Table for a unique constraint
bound to a single column, it is recommended to use the @Column.unique approach.
|
@Entity
@Table(name="EMPLOYEES",
uniqueConstraints = {@UniqueConstraint(columnNames={"email", "emp_code"})})
public class Employee implements Serializable {
...
}
|
@Column - Declaring column attributes
The column(s) used for a property mapping can be defined using the @Column annotation. You can use this
annotation at the property level.
|
@Entity
@Table(name="EMPLOYEES")
public class Employee implements Serializable {
@Id
@Column(name="EMP_ID")
private Long empId;
private String name;
private String department;
private Long salary;
@Column(name="JOINED_ON")
private Date joinedOn;
...
}
|
In the above example, EMP_ID table column will be mapped to empId property. Incase if the table column names
are exactly matching with property names, you dont need to specify @Column annotation. By default hibernate maps them.
|