Monday, June 4, 2012

Hibernate: Saving Collections

We have a Employee Class in which we have class field as empId,empName and addresses.
suppose an Employee can have multiple address, in our example we have considered that
Employee have office address as well as home address.
for saving these address we have used Set collection in our example.
Here is the Employee Class
//Employee.java

package com.test;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int empid;
 
 @Column(name="EMPLOYEE_NAME")
 private String empName;
 
 @ElementCollection
 private Set
addresses = new HashSet
(); public Set
getAddresses() { return addresses; } public void setAddresses(Set
addresses) { this.addresses = addresses; } public int getEmpid() { return empid; } public void setEmpid(int empid) { this.empid = empid; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } }
Here we have address class which is marked as @Embeddable
package com.test;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Address {
 
 @Column(name="STREET")
 private String street;
 
 @Column(name="CITY")
 private String city;
 
 @Column(name="PINCODE")
 private String pincode;
 
 @Column(name="STATE")
 private String state;
 
 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 getPincode() {
  return pincode;
 }
 public void setPincode(String pincode) {
  this.pincode = pincode;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 
}

for persisting these classes we need a hibernate configuration to our database here I used MySQL as database
look at Hibernate.cfg.xml
<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <mapping class="com.test.Address"/>
        <mapping class="com.test.Employee"/>
        
    </session-factory>

</hibernate-configuration>

now we are ready to test our example here we have our main class
package com.test;

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

public class Main {

 
 public static void main(String[] args) {
  Employee emp1 = new Employee();
  emp1.setEmpName("Rajkumar Singh");
  
  Employee emp2 = new Employee();
  emp2.setEmpName("Sharad Singh");
  
  Address homeAddress = new Address();
  homeAddress.setCity("Bareilly");
  homeAddress.setStreet("121");
  homeAddress.setPincode("201301");
  homeAddress.setState("UP");
  
  Address officeAddress = new Address();
  officeAddress.setCity("Noida");
  officeAddress.setStreet("131");
  officeAddress.setPincode("201302");
  officeAddress.setState("UP");
  
  emp1.getAddresses().add(homeAddress);
  emp1.getAddresses().add(officeAddress);
  
  SessionFactory sf = new Configuration().configure().buildSessionFactory();
  Session session = sf.openSession();
  session.beginTransaction();
  session.save(emp1);  // saving emp1 
  session.getTransaction().commit();
  session.close();
  

 }

}

we we ran our main class two table have generated in the database with the name of Employee and Employee_addresses.

look at the console output
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: insert into Employee (EMPLOYEE_NAME) values (?)
Hibernate: insert into Employee_addresses (Employee_empid, CITY, PINCODE, STATE, STREET) values (?, ?, ?, ?, ?)
Hibernate: insert into Employee_addresses (Employee_empid, CITY, PINCODE, STATE, STREET) values (?, ?, ?, ?, ?)
Post a Comment