Skip to main content

Hibernate : How to use @Entity annotation

How to use @Entity annotation in Hibernate

Suppose we want to make a User domain with the following fields

  • Id
  • Name
  • Age
  • Address
  • Gender
  • Email
  • Mobile
We can create tell the hibernate to register this Domain class as a Hibernate Entity object by adding @Entity annotation at the class level.

package com.ekiras.domian;

import com.ekiras.enums.Gender;
import javax.persistence.Entity;

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Integer age;
private String address;
private Gender gender;
private String email;
private Long mobile;

// GETTERS and SETTERS
}


So what the above line means is that, hibernate treats the class User as a Hibernate Persistence Entity. We will look at the @Id and @GeneratedValue annotations in a short while.

@Entity annotation looks like the following

@Documented
@Target(TYPE)
@Retention(RUNTIME)
public @interface Entity {
String name() default "";
}
Here the name field is optional and the can be used for the following

(Optional) The entity name. Defaults to the unqualified name of the entity class. This name is used to refer to the entity in queries. The name must not be a reserved literal in the Java Persistence query language.

So hibernate will create a table in Mysql like following


Comments