Skip to main content

Saving Collections in Hibernate with Example

Hibernate uses @ElementCollection annotation to save collection object.

Let’s consider we have Address Object.
User may have many address so we will add all address in collection and after that we will save in database.

syntax:

1
2
@ElementCollection
Set<Address> listoAddress=new HashSet<>();

Create below file

1. Address.java
2. User_info_data.java
3. Hibernate.cfg.xml
4. CreateUserData.java

Address.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.spy.hashset;
 
import javax.persistence.Embeddable;
import javax.persistence.Entity;
 
@Embeddable
public class Address
{
 
	String society;
	String city;
	int pincode;
 
 
	public String getSociety() 
	{
		return society;
	}
 
	public void setSociety(String society) 
	{
		this.society = society;
	}
 
	public String getCity() 
	{
		return city;
	}
 
	public void setCity(String city)
	{
		this.city = city;
	}
 
	public int getPincode() 
	{
		return pincode;
	}
 
	public void setPincode(int pincode) 
	{
		this.pincode = pincode;
	}
 
}

User_info_data.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.spy.hashset;
 
import java.util.HashSet;
import java.util.Set;
 
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class User_info_data 
{
 
	@Id @GeneratedValue(strategy=GenerationType.AUTO)
	int id;
 
	String userid;
	public String getUserid() {
		return userid;
	}
 
 
	public void setUserid(String userid) {
		this.userid = userid;
	}
 
 
	String name;
 
 
	@ElementCollection
	Set<Address> listoAddress=new HashSet<>();
 
 
	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<Address> getListoAddress() {
		return listoAddress;
	}	
 
	public void setListoAddress(Set<Address> listoAddress) {
		this.listoAddress = listoAddress;
	}
}

Hibernate.cfg.xml


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/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://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
 
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
 
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
 
 
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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>
 
<mapping class="com.spy.hashset.Address"/>
 
<mapping class="com.spy.hashset.User_info_data"/>
 
 
</session-factory>
 
</hibernate-configuration>

CreateUserData.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 
package com.spy.hashset;
 
 
import java.util.Set;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
 
public class CreateUserData 
{
 
	public static void main(String[] args)
     {
 
	User_info_data user=new User_info_data();
 
	user.setUserid("vivek007");
	user.setName("Vivek Patel");
 
 
	Address home=new Address();
	home.setSociety("rupani divdi");
	home.setCity("bhavnagar");
	home.setPincode(1234);
 
	//gettting list of address of Set collection
 
	Address office=new Address();
	office.setSociety("pune city");
	office.setCity("pune");
	office.setPincode(1212);
 
	//adding object into collection
	user.getListoAddress().add(home);
	user.getListoAddress().add(office);
 
       SessionFactory sf=new Configuration().configure().buildSessionFactory();
 
       Session session=sf.openSession();
 
       session.beginTransaction();
 
       session.save(user);
 
       session.getTransaction().commit();
 
       session.close();
 
	}	
 
}
1
2
3
Output: Hibernate: insert into User_info_data (name, userid) values (?, ?)
Hibernate: insert into User_info_data_listoAddress (User_info_data_id, city, pincode, society) values (?, ?, ?, ?)
Hibernate: insert into User_info_data_listoAddress (User_info_data_id, city, pincode, society) values (?, ?, ?, ?)

See User_info_data and User_info_data_listoAddress table in MySQL

User_info_data
user_info_data
User_info_data_listoAddress
address
 


Note:
In above case name of User_info_data and User_info_data_listoAddress table given by hibernate based on Your Entity class and variable name.

If you want to give your own name then we use @JoinTable and @JoinColumn

syntax:

1
@JoinTable(name="Table_name", joinColumns=@JoinColumn(name="Column_name"))

User_info_data


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.spy.hashset;
 
import java.util.HashSet;
import java.util.Set;
 
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
 
@Entity
public class User_info_data 
{
 
	@Id @GeneratedValue(strategy=GenerationType.AUTO)
	int id;
 
	String userid;
	public String getUserid() {
		return userid;
	}
 
 
	public void setUserid(String userid) {
		this.userid = userid;
	}
 
 
	String name;
 
	@ElementCollection
	@JoinTable(name="user_address", joinColumns=@JoinColumn(name="user_id")) 
 
	Set<Address> listoAddress=new HashSet<>();
 
 
	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<Address> getListoAddress() {
		return listoAddress;
	}
 
 
	public void setListoAddress(Set<Address> listoAddress) {
		this.listoAddress = listoAddress;
	}	
}

Now if you will run this program you can see output like this.

Output:

Hibernate: insert into User_info_data (name, userid) values (?, ?)

Hibernate: insert into user_address (user_id, city, pincode, society) values (?, ?, ?, ?)

Hibernate: insert into user_address (user_id, city, pincode, society) values (?, ?, ?, ?)

Database table:

User_info_data
user_info_data
user_address
address