Hibernate One to Many Bi-directional Mapping
In this section, you will learn how to do One to Many Bi-Directional Mapping in Hibernate.
In bi-directional mapping, the parent table can be retrieved by the child table and the child table can be retrieved by the parent table. Means retrieval can be done in both direction or bi-directional. That's why we call it bi-directional mapping.
EXAMPLE
In the given below example, address table access the employee table to insert the record. Due to bi-directional nature, employee table can also insert the records in both the tables.
The project hierarchy and the jar file used is given below :
The sql query used to create the two database table is given below :
CREATE TABLE `employee` ( `employee_id` bigint(10) NOT NULL auto_increment, `firstname` varchar(50) default NULL, `lastname` varchar(50) default NULL, `cell_phone` varchar(15) default NULL, `address_id` bigint(20) default NULL, PRIMARY KEY (`employee_id`), KEY `FK_employee` (`address_id`), CONSTRAINT `FK_employee` FOREIGN KEY (`address_id`) REFERENCES `address` (`address_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 CREATE TABLE `address` ( `address_id` bigint(20) NOT NULL auto_increment, `street` varchar(50) default NULL, `city` varchar(50) default NULL, `state` varchar(50) default NULL, `country` varchar(50) default NULL, PRIMARY KEY (`address_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
CODE
hibernate.cfg.xml ( /src/hibernate.cfg.xml )
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://192.168.10.13:3306/anky</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">thread</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">validate</property> <mapping class="net.roseindia.Address" /> <mapping class="net.roseindia.Employee" /> </session-factory> </hibernate-configuration>
Address.java ( /src/net/roseindia/Address.java )
package net.roseindia; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "address") public class Address { @Id @GeneratedValue @Column(name = "address_id") private Long addressId; @Column(name = "street") private String street; @Column(name = "city") private String city; @Column(name = "state") private String state; @Column(name = "country") private String country; @OneToMany(cascade={CascadeType.ALL}) @JoinColumn(name="address_id") private Set<Employee> employees; public Long getAddressId() { return addressId; } public void setAddressId(Long addressId) { this.addressId = addressId; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Set<Employee> getEmployees() { return employees; } public void setEmployees(Set<Employee> employees) { this.employees = employees; } }
Employee.java ( /src/net/roseindia/Employee.java )
package net.roseindia; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="employee") public class Employee { @Id @GeneratedValue @Column(name="employee_id") private Long employeeId; @Column(name="firstname") private String firstname; @Column(name="lastname") private String lastname; @Column(name="cell_phone") private String cellphone; @ManyToOne @JoinColumn(name="address_id") private Address address; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Employee() {} public Employee(String firstname, String lastname, String phone) { this.firstname = firstname; this.lastname = lastname; this.cellphone = phone; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getCellphone() { return cellphone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } }
ManageEmployee.java ( /src/net/roseindia/ManageEmployee.java )
package net.roseindia; import java.util.HashSet; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class ManageEmployee { private static SessionFactory sf; private static ServiceRegistry serviceRegistry; public static void main(String[] args) { try { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()).buildServiceRegistry(); sf = configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } System.out.println("Hibernate One to Many Bi-Directional Mapping Example "); Session session = sf.openSession(); session.beginTransaction(); //Address to Employee mapping System.out.print(".....Address to Employee mapping......"); Address address = new Address(); address.setStreet("West Bank"); address.setCity("New Delhi"); address.setState("Delhi"); address.setCountry("India"); Employee e1 = new Employee("Romesh", "Thapar", "9999999999"); Employee e2 = new Employee("Smita", "Khanna", "3333333333"); address.setEmployees(new HashSet<Employee>()); address.getEmployees().add(e1); address.getEmployees().add(e2); session.save(address); //Employee to Address mapping System.out.print(".....Employee to Address mapping...."); Address address1 = new Address(); address1.setStreet("Lake Gardens"); address1.setCity("Kolkata"); address1.setState("West Bengal"); address1.setCountry("India"); session.save(address1); Employee e3 = new Employee("Rakesh", "Sharma", "9999999999"); Employee e4 = new Employee("Kapil", "Kaushal", "3333333333"); e3.setAddress(address1); e4.setAddress(address1); session.save(e3); session.save(e4); session.getTransaction().commit(); session.close(); } }
OUTPUT
After the above code execution, you can see the following lines in console :
Hibernate One to Many Bi-Directional Mapping Example .....Address to Employee mapping......Hibernate: insert into address (city, country, state, street) values (?, ?, ?, ?) Hibernate: insert into employee (address_id, cell_phone, firstname, lastname) values (?, ?, ?, ?) Hibernate: insert into employee (address_id, cell_phone, firstname, lastname) values (?, ?, ?, ?) .....Employee to Address mapping....Hibernate: insert into address (city, country, state, street) values (?, ?, ?, ?) Hibernate: insert into employee (address_id, cell_phone, firstname, lastname) values (?, ?, ?, ?) Hibernate: insert into employee (address_id, cell_phone, firstname, lastname) values (?, ?, ?, ?) Hibernate: update employee set address_id=? where employee_id=? Hibernate: update employee set address_id=? where employee_id=?
In employee table, you will get the following :
In address table, you will get the following :