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




Component Mapping using Annotations

A Component can also be mapped using annotation.

So we have an 'Employee' class and an 'Address' class. And their corresponding mapping files are 'Employee.hbm.xml' and 'Address.hbm.xml'

Now, by using annotation we can avoid the mapping files i.e. 'Employee.hbm.xml' and 'Address.hbm.xml'.

Let us see the modified 'Employee' and 'Address' class :


@Embeddable
class Address{
    String streetName;
    String city;
    String pinCode;

   ---Getters & Setters---
}


and refer it in the 'Employee' class:


@Entity(name="EMPLOYEE")
class Employee{
    @Id(name="ID")
    int id;
    @Column(name="NAME")
    String name;
    @Embedded
    Address address;

    ---Getters & Setters---
}


Since, Address is a Value Object(i.e. it cannot exist on its own), we have marked it with @Embeddable annotation.

Now, in the 'Employee' class, we have also put @Embedded just above 'Address address'. It tells Hibernate that 'Address' is a Value Object and should be linked.

So, with the use of annotation, we do not have to write the mapping files. And we can directly jump to the main method.


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSave {
   public static void main(String[] args) {

    static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    Address address = new Address();
    address.setStreetName("Walls Street");
    address.setCity("Delhi");
    address.setPinCode("110012");

    Employee employee = new Employee();
    employee.setId(1);
    employee.setName("Joe");
    employee.setAddress(address);
    session.save(employee);

    session.getTransaction().commit();

    session.close();
    sessionFactory.close();
  }
 }

The table structure would be like


ID NAME STREET_NAME CITY PIN_CODE
1 John Walls street Delhi 110012