Declaring a class as an entity and creating a table in the database – @Entity and @Table
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.
How to do it…
Perform the following steps to declare a class as a hibernate entity:
- Enter the following code on your editor:
@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.Note
If you build a session factory with the preceding code and the table name is not given, hibernate will create a table with the name
employee
, which is equal to the class name. - If we want a user-defined table name rather than a default name, we can use the
@Table
annotation. The following code shows us how to achieve this:@Entity @Table(name="tbl_employee") public class Employee { // Fields...