Hibernate One-to-Many XML Mapping Example
In this tutorial we are going to understand how to map a one-to-many association between Java objects and database tables using Hibernate framework. We will create a sample Hibernate-based application to manage the following entity relationship:
In this relationship,one row in a table can be mapped to multiple rows in another table. For example, think of a Bank where we have another table for Customer. A Bank can have multiple Customers, so here we can implement one-to-many Mapping.
Create Tables :
For this example, we used MYSQL Database. Create following two tables in MySQL.Each Bank can be associated with multiple Customer.
In this tutorial we are going to understand how to map a one-to-many association between Java objects and database tables using Hibernate framework. We will create a sample Hibernate-based application to manage the following entity relationship:
In this relationship,one row in a table can be mapped to multiple rows in another table. For example, think of a Bank where we have another table for Customer. A Bank can have multiple Customers, so here we can implement one-to-many Mapping.
Create Tables :
For this example, we used MYSQL Database. Create following two tables in MySQL.Each Bank can be associated with multiple Customer.
CREATE TABLE `BANK` ( `bank_id` BIGINT(20) NOT NULL AUTO_INCREMENT, `bank_name` VARCHAR(50) NOT NULL DEFAULT '0', PRIMARY KEY (`bank_id`) ); CREATE TABLE `CUSTOMER` ( `customer_id` BIGINT(10) NOT NULL AUTO_INCREMENT, `firstname` VARCHAR(50) NULL DEFAULT NULL, `lastname` VARCHAR(50) NULL DEFAULT NULL, `birth_date` DATE NULL DEFAULT NULL, `cell_phone` VARCHAR(15) NULL DEFAULT NULL, `bank_id` BIGINT(20) NULL DEFAULT NULL, PRIMARY KEY (`customer_id`), INDEX `FK_DEPT` (`bank_id`), CONSTRAINT `FK_BANK` FOREIGN KEY (`bank_id`) REFERENCES `bank` (`bank_id`) );
Project Structure :
Create a simple java project in Eclipse, and add hibernate related jar files to the classpath of the project. The final project structure is given below.
Create Model Classes :
Create two Pojo classes Bank.java and Customer.java to model the two tables BANK and CUSTOMER, respectively.
Bank.java
package com.javawebtutor.hibernate.model; import java.util.Set; public class Bank { private Long bankId; private String bankName; private Set<Customer> customers; public Long getBankId() { return bankId; } public void setBankId(Long bankId) { this.bankId = bankId; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public Set<Customer> getCustomers() { return customers; } public void setCustomers(Set<Customer> customers) { this.customers = customers; } }
I am using Set of Customers, so that every record is unique. We can also use List or Array for one-to-one mapping.
Customer.java
package com.javawebtutor.hibernate.model; import java.util.Date; public class Customer { private Long customerId; private String firstname; private String lastname; private Date birthDate; private String cellphone; private Bank bank; public Customer(String firstname, String lastname, Date birthDate, String cellphone) { this.firstname = firstname; this.lastname = lastname; this.birthDate = birthDate; this.cellphone = cellphone; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } 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 Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getCellphone() { return cellphone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } public Bank getBank() { return bank; } public void setBank(Bank bank) { this.bank = bank; } }
Hibernate Utility Class :
Create a utility class for creating Hibernate SessionFactory.
HibernateUtil.java
package com.javawebtutor.hibernate.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Create Hibernate Mapping Files :
Create two XML files bank.hbm.xml and customer.hbm.xml to map the JavaBean classes with the database tables.
bank.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="com.javawebtutor.hibernate.model"> <class name="Bank" table="BANK"> <id name="bankId" type="java.lang.Long" column="department_id"> <generator class="native" /> </id> <property name="bankName" column="bank_name" /> <set name="customers" table="CUSTOMER" inverse="true" lazy="true" fetch="select"> <key> <column name="bank_id" not-null="true" /> </key> <one-to-many class="com.javawebtutor.hibernate.model.Customer" /> </set> </class> </hibernate-mapping>
customer.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="com.javawebtutor.hibernate.model"> <class name="Customer" table="CUSTOMER"> <id name="customerId" column="customer_id"> <generator class="native" /> </id> <property name="firstname" /> <property name="lastname" column="lastname" /> <property name="birthDate" type="date" column="birth_date" /> <property name="cellphone" column="cell_phone" /> <many-to-one name="bank" class="com.javawebtutor.hibernate.model.Bank" fetch="select"> <column name="bank_id" not-null="true" /> </many-to-one> </class> </hibernate-mapping>
Create Hibernate Configuration File:
Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection details and the mapping files:
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> <!-- specify database driver --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url"> jdbc:mysql://localhost/hibernate</property> <!-- database username --> <property name="hibernate.connection.username">root</property> <!-- database password --> <property name="connection.password">mukesh</property> <!-- database dialect, different for different databases --> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property> <!-- true value shows SQL query that is generated by hibrnate --> <property name="show_sql">true</property> <!-- to bind hibernate session to current running java thread --> <property name="current_session_context_class">thread</property> <!-- path of hibernate mapping file --> <mapping resource="com/javawebtutor/hibernate/model/bank.hbm.xml"></mapping> <mapping resource="com/javawebtutor/hibernate/model/customer.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
Note:- Update the database username and password corresponding to your database settings.
Create a Test Program :
Following is code of the test program that persists some sample data.
Test.javapackage com.javawebtutor.hibernate.client; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.javawebtutor.hibernate.model.Bank; import com.javawebtutor.hibernate.model.Customer; import com.javawebtutor.hibernate.util.HibernateUtil; public class Test { public static void main(String[] args) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); Bank bank = new Bank(); bank.setBankName("HDFC"); session.save(bank); Date birthDate = new java.util.Date(); birthDate = new java.util.Date(83, 02, 22); Customer customer = new Customer("Mukesh", "Kumar", birthDate, "8939651567"); Customer customer1 = new Customer("Ravi", "Raj", birthDate, "12345678"); customer.setBank(bank); customer1.setBank(bank); session.save(customer); session.save(customer1); session.getTransaction().commit(); session.close(); } }
Output :
Now Run Test.java, you will get following output in the eclipse console.
SQL Output :
Result in the BANK table:
Result in the CUSTOMER table:
Download this example(src+lib) developed in eclipse
Related Articles