Program to demonstrate how to save collections into database using @ElementCollection, @JoinTable and @JoinColumn annotations in Hibernate Framework.
A simple POJO class (model) Customer.java
A simple POJO class (model) Address which is being used as a collection into Customer
Hibernate Configuration XML file
A simple Test.java
Output of the program :
Two tables created into database as below:
Table 1: Customer
Table 2: Customer_Address
Video tutorial to demonstrate how to persist Java Collections by @ElementCollection annotation in Hibernate using JPA.
A simple POJO class (model) Customer.java
package com.hubberspot.hibernate.examples;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity
public class Customer {
// @Id to tell Hibernate that we need this Model
// class having customerId as a Primary Key in the
// table Customer created by @Entity
@Id
private int customerId;
private String customerName;
// In order to save collections into database
// using Hibernate we use an annotation called as
// @ElementCollection which creates a seperate table
// for storing the contents of multiple addresses
// and associate a foreign key relationship with
// Customer table.
@ElementCollection
// In order to provide user friendly name to the
// separate table we use @JoinTable annotation which
// takes in name as the name user wants to provide to
// collections table. We can also provide name to foreign key
// using @JoinColumn annotation
@JoinTable(name="Customer_Address" , joinColumns=@JoinColumn(name="Customer_Id"))
private Set< Address >setOfAddresses = new HashSet< Address >();
public Set< Address >getSetOfAddresses() {
return setOfAddresses;
}
public void setSetOfAddresses(Set< Address >setOfAddresses) {
this.setOfAddresses = setOfAddresses;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
A simple POJO class (model) Address which is being used as a collection into Customer
package com.hubberspot.hibernate.examples;
import javax.persistence.Embeddable;
// @Embeddable tells Hibernate that Address object
// will be embedded into some other tables.
// The values of the properties will be populated
// into a table in which we want to embed the Address
@Embeddable
public class Address {
private String street;
private String city;
private String state;
private String zipCode;
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 getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
Hibernate Configuration XML file
<?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">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/customerdb</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- SQL dialect --> <property name="dialect"> org.hibernate.dialect.MySQL5Dialect </property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <!-- Mapping class entry into configuration xml for annotated classes --> <mapping class="com.hubberspot.hibernate.examples.Customer" /> </session-factory> </hibernate-configuration> |
A simple Test.java
package com.hubberspot.hibernate.examples;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
public static void main(String[] args) {
// Lets create a Customer Object
Customer customer = new Customer();
customer.setCustomerId(1);
customer.setCustomerName("Jonty");
// Lets create multiple addresses object which will be
// saved as a collections into a separate table
Address address1 = new Address();
address1.setStreet("Street Name 1");
address1.setCity("City Name 1");
address1.setState("State Name 1");
address1.setZipCode("Zip-Code Value 1");
Address address2 = new Address();
address2.setStreet("Street Name 2");
address2.setCity("City Name 2");
address2.setState("State Name 2");
address2.setZipCode("Zip-Code Value 2");
customer.getSetOfAddresses().add(address1);
customer.getSetOfAddresses().add(address2);
// SessionFactory gives us a factory of sessions
// Usually SessionFactory is been configured by the
// configuration file named as hibernate.cfg.xml
// buildSessionFactory() builds the sessionFactory for us
SessionFactory sessionFactory = new Configuration().
configure().buildSessionFactory();
// Session is created by calling openSession()
// method on SessionFactory object
Session session = sessionFactory.openSession();
session.beginTransaction();
// Our Transaction Code goes here
// i.e save, load , merge and remove
// Lets save our Customer object created
// above using sessions save method.
session.save(customer);
// Committing the transaction in order to save.
session.getTransaction().commit();
// Closing the session
session.close();
}
}
Output of the program :
Two tables created into database as below:
Table 1: Customer
Table 2: Customer_Address
Video tutorial to demonstrate how to persist Java Collections by @ElementCollection annotation in Hibernate using JPA.










