Hibernate - One to Many using Annotations
One to Many using Annotations
One to Many relationship can also be done using annotations in Hibernate. The advantage is that we don't have to use the mapping files for 'Employee' and 'Address' class.
Note : We have used a Set instead of List(As used in XML version of one to many) to see how Set works.
Let us define the classes below:
@Entity(name="EMPLOYEE")
class Employee {
@Id
@Column(name="ID")
String id;
@Column(name="NAME")
String name;
@OneToMany(mappedBy="employee", Cascade=CascadeType.ALL)
Set <Address> addressSet = new HashSet <Address> ();
--- getters and setters ---
}
An 'Employee' can have a multiple 'Address' objects. And in the 'Employee' class we have represented it as a 'Set':
Set <Address> addressSet
On top of the 'Set', we have put
@OneToMany(mappedBy="employee", Cascade=CascadeType.ALL)
Which establishes an One to Many relationship between Employee and Set of Address. And 'mappedBy="employee"' says it needs to search in the 'Address' class for the 'employee' object, which it needs to map to.
The 'Address' class is declared below:
@Entity(name="ADDRESS")
class Address{
@Id
@Column(name="ADDRESS_ID")
int addressId;
@Column(name="STREET_NAME")
String streetName;
@Column(name="CITY")
String city;
@Column(name="PIN_CODE")
String pinCode;
@ManyToOne
@JoinColumn(name="ID")
Employee employee;
---Getters & Setters---
}
Placing @ManyToOne establishes a bi-directional relationship.
@ManyToOne
@JoinColumn(name="ID")
Employee employee;
The name="ID" specified in @JoinColumn annotation says 'ID' is the foreign key for 'ADDRESS' table. And should have a primary key - foreign key relationship with 'Employee'.
Now, let us define 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();
List <Address> addressList = new ArrayList <Address>();
Address localAddress = new Address();
localAddress.setStreetName("Walls Street");
localAddress.setCity("Delhi");
localAddress.setPinCode("110012");
addressList.add(localAddress);
Address permanentAddress = new Address();
permanentAddress.setStreetName("Murugeshpalya");
permanentAddress.setCity("Bangalore");
permanentAddress.setPinCode("560019");
addressList.add(permanentAddress);
Employee employee = new Employee();
employee.setId(1);
employee.setName("Joe");
employee.setAddressList(addressList);
session.save(employee);
session.save(localAddress);
session.save(permanentAddress);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
EMPLOYEE
ADDRESS
ID |
ADDRESS_ID |
STREET_NAME |
CITY |
PIN_CODE |
1 |
1 |
Walls street |
Delhi |
110012 |
1 |
2 |
Murugeshpalya |
Bangalore |
560019 |