Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate4 Hibernate One to many XML mapping array Example

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate One to many XML mapping array Example

Advertisement
In this section, you will learn how to do one to many mapping using array to retain mapping order in Hibernate.

Hibernate One to many XML mapping <array> Example

In this section, you will learn how to do one to many mapping using array to retain mapping order in Hibernate.

In the previous one to many example using hibernate , multiple employees mapped with a address. For this we purpose we used java.util.Set. But the mapping order is not preserved in this case which is very important in some cases.

For this purpose, we use array. And also we need to add indx column specially for this purpose. This column store the index value for each column. This will helps us in conserving order of records while retrieving. In most cases, where we need to retain order, we use java.util.List because the size of the array can not be grow dynamically but it can grow dynamically in the case of List. Array is rarely used where we need to map for legacy applications.

EXAMPLE

In the below figure, the address_id is the foreign key to the table employee. With the help of address_id , we are here doing one to many mapping. The logic behind using this mapping in below example is - many employees can have the same street, city, state ,country as address. Only the house number differentiate the two people addresses. So address_id in employee table can have many same address ids which indicates to the same address in the address table.

In this example, we are inserting data into two table simultaneously which are correlated to each other. Here address table holding the data of the unique addresses, each having an unique id. This unique id is used to connect the address to the employee table's address id. This indicates the address of the employee. In conclusion, many employee can have the same address (except house/flat numbers). For example : Two people may have address- Salt Lake, Kolkata, West Bengal, India.

The project hierarchy and jar file used is given below :

Database table queries :

The query used to create address table is given below :

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 

The query used to create employee 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, 
`indx` int(11) 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 

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>

</session-factory>
</hibernate-configuration>

Address.java( /src/net/roseindia/Address.java )

package net.roseindia;

public class Address {

private Long addressId;

private String street;

private String city;

private String state;

private String country;

private Employee[] employees;

public Employee[] getEmployees() {
return employees;
}

public void setEmployees(Employee[] employees) {
this.employees = 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;
}

}

Address.hbm.xml( /src/net/roseindia/Address.hbm.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 package="net.roseindia">
<class name="Address" table="address">
<id name="addressId" column="address_id">
<generator class="native" />
</id>
<property name="street" column="street"/>
<property name="city" column="city"/>
<property name="state" column="state"/>
<property name="country" column="country"/>
<array name="employees" table="employee"
inverse="false" cascade="all">
<key>
<column name="address_id" not-null="true" />
</key>
<list-index column="indx" />
<one-to-many class="net.roseindia.Employee" />
</array>
</class>
</hibernate-mapping>

Employee.java( /src/net/roseindia/Employee.java )

package net.roseindia;

public class Employee {
private Long employeeId;

private String firstname;

private String lastname;

private String cellphone;

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;
}

}

Employee.hbm.xml( /src/net/roseindia/Employee.hbm.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 package="net.roseindia">

<class name="Employee" table="employee">
<id name="employeeId" column="employee_id">
<generator class="native" />
</id>

<property name="firstname" column="firstname"/>
<property name="lastname" column="lastname" />
<property name="cellphone" column="cell_phone" />

<many-to-one name="address" class="net.roseindia.Address" fetch="select">
<column name="address_id" not-null="true" />
</many-to-one>

</class>
</hibernate-mapping>

ManageEmployee.java( /src/net/roseindia/ManageEmployee.java)

package net.roseindia;

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().addResource("net/roseindia/Address.hbm.xml").addResource("net/roseindia/Employee.hbm.xml");
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 XML Mapping using Array********");
Session session = sf.openSession();
session.beginTransaction();

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 Employee[] {e1, e2});

session.save(address);

session.getTransaction().commit();
session.close();
}
}

OUTPUT

In the console, you will get the following lines :

********Hibernate One to Many XML Mapping using Array********
Hibernate: insert into address (street, city, state, country) values (?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id) values (?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id) values (?, ?, ?, ?)
Hibernate: update employee set address_id=?, indx=? where employee_id=?
Hibernate: update employee set address_id=?, indx=? where employee_id=?

In the employee table, you will get the following records :

In the address table, you will get the following records :

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 28, 2012

Related Tutorials

Discuss: Hibernate One to many XML mapping array Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com