We need a class to be declared as an entity for hibernate to use it. Hibernate considers the class as a persistent class if it is annotated with the
@Entity
annotation.
Perform the following steps to declare a class as a hibernate entity:
@Entity public class Employee { // Fields and getter/setter }
Here, we annotate a class, Employee
, with the @Entity
annotation. As a result, hibernate considers the current class eligible to be persisted.
@Table
annotation. The following code shows us how to achieve this:@Entity @Table(name="tbl_employee") public class Employee { // Fields and getter/setter }
Here, we give name="tbl_employee"
as a parameter in the @Table
annotation. So, hibernate will override the default table name with the name "tbl_employee"
.
There is another attribute available with @Table
annotations; let's take a look at it.
This attribute is called
uniqueConstraints
. It is used when we need the UNIQUE
key constraint with multiple fields.
The following code shows how to do this:
@Entity @Table(name = "tbl_employee", uniqueConstraints = @UniqueConstraint(columnNames = { "id" , "empCode"})) public class Employee { @Id private long id; @Column private String empCode; // Fields and getter/setter }
When a SessionFactory
is created for the first time and property hbm2ddl.auto
is set to create
, hibernate will execute the following queries to create a table and the unique key constraints:
Hibernate: drop table if exists tbl_employee Hibernate: create table tbl_employee (id bigint not null, empCode varchar(255), primary key (id)) Hibernate: alter table tbl_employee add constraint UK_3r763mmnyundobvaiqjv6lnj1 unique (id, empCode)
When the table is created using the preceding code, hibernate will create the UNIQUE
key using two fields: id
and empCode
.
Take a look at the following script belonging to the table created by hibernate to understand uniqueConstraints
:
CREATE TABLE `tbl_employee` ( `id` bigint(20) NOT NULL, `empCode` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`,`empCode`) );
Hibernate uses the declared annotation at the time of compilation to get the information applied to the Java code. You can't persist a class if it is not annotated with @Entity
or defined in *.hbm.xml
.
The @Table
annotation is an optional annotation and is used when the custom table name is required.