Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Hibernate Mapping using Annotations

Mapping can also be achieved using annotations. Instead of writing the mapping file Employee.hbm.xml, we can directly define the mapping in the 'Employee' class itself using Annotations.

Let us see below how we can map the 'Employee' class:


@Entity(name="EMPLOYEE")
class Employee{
   @Id(name="EMP_ID")
   int empId;
   @Column(name="NAME")
   String name;
   ---Getters & Setters---
}


The above code is almost same as the above :

We have put '@Entity' just above 'class Employee', which tells Hibernate that 'Employee' class needs to be treated as an 'Entity' and should be saved to a table named 'EMPLOYEE'.

@Entity(name="EMPLOYEE")

Next, we have @Id annotation above 'int empId'. Which tells Hibernate that 'empId' should be treated as a primary key and the column name in the database would be 'EMP_ID'.

Finally, we have the @Column annotation which tells Hibernate that the 'name' field should be treated as a column and should be named as 'NAME' on the database side.


Note : If you don't specify 'name' attribute for the any annotation, the name would be taken from the java class. i.e. if we do not specify 'name="EMPLOYEE"' in @Entity then the name of the table would be 'Employee', which is the java class name.