Hibernate - SPLessons

Hibernate One to Many

Home > Lesson > Chapter 24
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Hibernate One to Many

Hibernate One to Many

shape Description

Hibernate One to Many, means object of one class and object of other classes relationship. To apply the Hibernate One to Many relationship between two POJO class following are the conditions needed.

shape Examples

Suppose there are two classes Employee and Address. To apply the one-to-one relationship from Employee object to multiple Address objects.
  • Create the Project directory structure.
  • Create the Persistence classes.
Employee.java [java]package com.itoolsinfo; import java.util.Set; public class Employee { private int id; private String name; private Set address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getAddress() { return address; } public void setAddress(Set address) { this.address = address; } } [/java] Here the developer created the class Employee with the variables name and address, set and get methods are used on the variables. Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, one can define get methods to access these variables, and set methods to modify them. Address.java [java]package com.itoolsinfo; public class Address { private int streetNumber; public int getStreetNumber() { return streetNumber; } public void setStreetNumber(int streetNumber) { this.streetNumber = streetNumber; } private String city, village, street; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getVillage() { return village; } public void setVillage(String village) { this.village = village; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } [/java] Here the developer created the class Address with their variables such as streetNumber, city, village. Set and Get operations were performed on this variables.
  • Map all POJO classes in mapping file that is employee.hbm.xml.
[xml]<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”> <hibernate-mapping> <class name=”com.itoolsinfo.Employee” table=”employee5”> <id name=”id” column=”id”> <generator class=”increment”></generator> </id> <property name=”name” length=”14”/> <set name=”address” cascade=”all”> <key column=”eid”/> <one-to-many class=”com.itoolsinfo.Address”/> </set> </class> <class name=”com.itoolsinfo.Address”table=”address8” > <id name=”streetNumber”> </id> <property name=”village” length=”14”/> <property name=”street”length=”14”/> <property name=”city” length=”14”></property> </class> </hibernate-mapping> [/xml]
  • Configure the mapping file in Configuration file.
hibernate.cfg.xml [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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping resource="employee.hbm.xml"/> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the SPLessons class and store the POJO class objects to perform database operations.
SPLessons.java [java]package com.itoolsinfo; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session=factory.openSession(); // To insert parent Employee class property values. Employee employee=new Employee(); employee.setId(2); employee.setName(" jhosf " ); // To insert multiple Address class object values. Address address= new Address(); address.setStreetNumber(330); address.setStreet("Hariharapuram"); address.setVillage("BNReddy nagar"); address.setCity("LB nagar"); Address address1= new Address(); address1.setStreetNumber(314); address1.setStreet("yousufguda"); address1.setVillage("Ameerpet"); address1.setCity("Hyderabad"); // To add the address class objects in collection variable. Set <Address> set=new HashSet <Address>(); set.add(address); set.add(address1); // To set the collection variable to Employee class object. employee.setAddress(set); Transaction transaction=session.beginTransaction(); session.save(employee); transaction.commit(); session.close(); } } [/java] Here the developer created the class SPLessons to perform database operations as mentioned in the comments of the code.
  • See the output in command prompt.
  • See the output in database table using following command.
[sql]select * from employee;[/sql] [sql]select * from address;[/sql]
Suppose there are two classes Employee and Address. Apply one-to-one relationship from Employee object to multiple Address objects. Using the List type, add the index column in table.
  • Create the Project directory structure.
  • Create the Persistence classes.
Employee.java [java]package com.itoolsinfo; import java.util.List; public class Employee { private int id; private String name; private List address; public List getAddress() { return address; } public void setAddress(List address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } [/java] Here created the class Employee with variables name and address, where set and get methods are used to perform action on this variables. Address.java [java]package com.itoolsinfo; public class Address { private int streetNumber; public int getStreetNumber() { return streetNumber; } public void setStreetNumber(int streetNumber) { this.streetNumber = streetNumber; } private String city, village, street; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getVillage() { return village; } public void setVillage(String village) { this.village = village; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } [/java] Here the developer created the class Address with their variables such as streetNumber, city, village. Set and Get operations were performed on this variables.
  • Map the POJO classes in mapping file that is employee.hbm.xml.
[xml]<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <hibernate-mapping> <class name="com.itoolsinfo.Employee"table="employee"> <id name="id" column="id"> <generator class="increment"></generator> </id> <property name="name" length="14"/> <list name="address" cascade="all"> <key column="eid"/> <index column="type"/> <one-to-many class="com.itoolsinfo.Address"/> </list> </class> <class name="com.itoolsinfo.Address" table="address" > <id name="streetNumber"/> <property name="village" length="14"> <property name="street" length="14"> <property name="city" length="14"></property> </class> /hibernate-mapping [/xml]
  • Configure the mapping file in Configuration file.
hibernate.cfg.xml [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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping resource="employee.hbm.xml"/> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the SPLessons class and store the POJO class objects to perform the Database operations.
SPLessons.java [java]package com.itoolsinfo; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session=factory.openSession(); // To insert parent Employee class property values. Employee employee=new Employee(); employee.setId(1); employee.setName(" joshaf " ); Employee employee1=new Employee(); employee1.setId(2); employee1.setName(" jhon " ); // To insert multiple Address class object values. Address address= new Address(); address.setStreetNumber(330); address.setStreet("Hariharapuram"); address.setVillage("BNReddy nagar"); address.setCity("LB nagar"); Address address1= new Address(); address1.setStreetNumber(314); address1.setStreet("yousufguda"); address1.setVillage("Ameerpet"); address1.setCity("Hyderabad"); // To add the address class objects in collection variable. List <Address> list=new ArrayList <Address>(); list.add(address); List <Address> list1=new ArrayList <Address>(); list1.add(address1); // To set the collection variable to Employee class object. employee.setAddress(list); employee1.setAddress(list1); Transaction transaction=session.beginTransaction(); // To save the all employee class objects into the session object. session.save(employee); session.save(employee1); transaction.commit(); session.close(); } } [/java] SPLessons class is used to perform database operations as mentioned in the comments of the code.
  • See the Output in command prompot.
  • See the Output in Database table using following command.
[sql]select * from employee;[/sql] [sql]select * from address;[/sql]
In One-to-many relationship two annotations are used in Parent class. 1. @OneToMany(targetEntity="child class object of class",cascade=CasecadeType.ALL) It indicates mapping of child class object to Parent class object. 2. @JoinColumn(name="primary key column", name="foreign key column") Used to map the primary column in two tables. If there are two classes Employee and Address and want to apply one-to-one relationship from Employee object to multiple Address objects using Annotations and using Primary key column is id,
  • Create the Project directory structure.
  • Create the persistence classes.
Employee.java [java]package com.itoolsinfo; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="employee") public class Employee { @Id private int id; @Column(name="name") private String name; @OneToMany(targetEntity=Address.class,cascade=CascadeType.ALL) @JoinColumn(name="eid") private Set address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getAddress() { return address; } public void setAddress(Set address) { this.address = address; } } [/java] Here the developer explained the code with same example, but here used annotaions, the purpose of annotation is to reduce the code. The @Table comment permits you to indicate the points of interest of the table that will be utilized to hold on the element in the database. The @Table explanation gives four traits, permitting you to abrogate the name of the table, its inventory, and its composition, and uphold exceptional imperatives on sections in the table. Address.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="address") public class Address { @Id private int streetNumber; public void setStreetNumber(int streetNumber) { this.streetNumber = streetNumber; } public int getStreetNumber() { return streetNumber; } public void setStreetNumber1(int streetNumber) { this.streetNumber = streetNumber; } @Column(name="street") private String street; @Column(name="village") private String village; @Column(name="city") private String city; /*public int getId() { return id; } public void setId(int id) { this.id = id; }*/ public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getVillage() { return village; } public void setVillage(String village) { this.village = village; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } [/java] Every element bean will have an essential key, which you comment on the class with the @Id comment. The essential key can be a solitary field or a mix of different fields relying upon your table structure. As a matter of course, the @Id comment will naturally decide the most suitable essential key era technique to be utilized however you can abrogate this by applying the @GeneratedValue explanation which takes two parameters system and generator
  • Configure all classes in Configuration file.
hibernate.cfg.xml [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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping resource="employee.hbm.xml"/> </session-factory> </hibernate-configuration> [/xml]
  • Create the SPLessons class and store the POJO class objects to perform database operations.
SPLessons.java [java]package com.itoolsinfo; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session=factory.openSession(); // To insert parent Employee class property values. Employee employee=new Employee(); employee.setId(2); employee.setName(" jhosf " ); // To insert multiple Address class object values. Address address= new Address(); address.setStreetNumber(330); address.setStreet("Hariharapuram"); address.setVillage("BNReddy nagar"); address.setCity("LB nagar"); Address address1= new Address(); address1.setStreetNumber(314); address1.setStreet("yousufguda"); address1.setVillage("Ameerpet"); address1.setCity("Hyderabad"); // To add the address class objects in collection variable. Set <Address> set=new HashSet <Address>(); set.add(address); set.add(address1); // To set the collection variable to Employee class object. employee.setAddress(set); Transaction transaction=session.beginTransaction(); session.save(employee); transaction.commit(); session.close(); } } [/java]
  • See the output in command prompot.
  • See the output in database table using following command.
[sql]select * from employee;[/sql] [sql]select * from address;[/sql]

Summary

shape Points

  • Hibernate One to Many - Collection property should be in the parent class in One-To-Many relationship.
  • Hibernate One to Many - collection needs to be map in parent class of the mapping file.
  • Set, List, Map are the collections will be used.