<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;"><b style="color: #351c75; font-weight: normal;">Now we’ll learn about the Saving Collections in Hibernate with Example.</b></p>
<div style="color: #073763;">In the <a href="https://dineshonjava.com/p/value-types-and-embedding-objects.html">previous tutorial</a>, we learned about Embedding value type object.</p>
<div id="ads-id" align="center"></div>
</div>
<div style="color: #073763;">Now what will be doing when there are a lot of embeddable objects instead of the single embeddable objects, In previous we have used two embeddable objects in the <b>UserDetails </b>class.</div>
<div style="color: #073763;"></div>
<div style="color: #073763;">Suppose we want to keep tracks all addresses of a user, so think about one minute how to get.</div>
<p>Lets we will use the Collection for that.</p>
<p>1. In this code snip, User has one address</p>
<div style="color: blue;">class UserDetails{</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private int userId;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private Address address;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;">}</div>
<p>2. In this code snip User has two addresses</p>
<div style="color: blue;">class UserDetails{</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private int userId;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private Address address1;</div>
<div style="color: blue;"> private Address address2;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<p>}</p>
<p>3. In this code snip User has more than two addresses</p>
<div style="color: blue;">class UserDetails{</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private int userId;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private Address address1;</div>
<div style="color: blue;"> private Address address2;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private Address addressN;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;">}</div>
<p>In the third case how to manage the records about addresses for that user, now for managing this type of problems we have to use the collection, we do not need to care about how many of the addresses user has. Let&#8217;s see there is the same change in the code for that&#8230;</p>
<div style="color: blue;">class UserDetails{</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private int userId;</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;"> private List<;Address>; addresses = new ArrayList<;Address>;();</div>
<div style="color: blue;"> &#8212;&#8211;</div>
<div style="color: blue;">}</div>
<div style="color: #20124d;">Hibernate provides the facility to persist the collections. A collection can be a list, set, map, collection, sorted set, sorted map. java.util.List, java.util.Set, java.util.Collection, java.util.SortedSet, java.util.SortedMap etc. are the real interface types to declared the persistent collection-valued fields. Hibernate injects persistent collections based on the type of interface. The collection instances usually behave likes the types of value behaviour. Instances of collections are auto persisted if a persistent object refers it and are deleted automatically if it is not referred through. Elements of collection may shift from one table to another when a persistent object passed the collection to another persistent object.</div>
<p>We look following example of <b>Object of Entity Type:</b><b style="color: #351c75; font-weight: normal;"> </b><br />
<b style="color: #351c75; font-weight: normal;"><br />
</b></p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<div style="color: #274e13;"><b>@Entity</b></div>
<div style="color: #274e13;"><b>@Table(name=&#8221;TBL_USER_DETAILS</b><b>&#8220;) </b></div>
<p>public class UserDetails{<br />
<b style="color: #274e13;">@Id</b></p>
<div style="color: #274e13;"><b> @Column(name=&#8221;USER_ID&#8221;, type=&#8221;INTEGER&#8221;)</b><br />
<b> @GeneratedValue(strategy=GenerationType.AUTO) </b></div>
<p>private long userId;<br />
<b style="color: #274e13;">@Column(name=&#8221;USER_NAME&#8221;, type=&#8221;String&#8221;)</b><br />
private String userName;<br />
<b style="color: #274e13;">@ElementCollection<br />
</b>private Collection<;Address>; lisOfAddresses = new ArrayList<;Address>;();<br />
public Collection<;Address>; getLisOfAddresses() {<br />
return lisOfAddresses;<br />
}<br />
public void setLisOfAddresses(Collection<;Address>; lisOfAddresses) {<br />
this.lisOfAddresses = lisOfAddresses;<br />
}<br />
public int getUserId() {<br />
return userId;<br />
}<br />
public void setUserId(int userId) {<br />
this.userId = userId;<br />
}<br />
public String getUserName() {<br />
return userName;<br />
}<br />
public void setUserName(String userName) {<br />
this.userName = userName;<br />
}<br />
public String toString()<br />
{<br />
return &#8220;[User Name: &#8220;+userName+&#8221;n Office Address: &#8220;+lisOfAddresses+&#8221;]&#8221;;<br />
}<br />
}</p>
</div>
<p><b style="color: #274e13;">@ElementCollection:</b><br />
<b>Target:</b><br />
Fields (including property get methods)Defines a collection of instances of a basic type or embeddable class. Must be specified if the collection is to be mapped by means of a collection table.<br />
<b>Address.java</b></p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">package com.sdnext.hibernate.tutorial.dto;</p>
<p>import javax.persistence.Column;<br />
import javax.persistence.Embeddable;</p>
<p><b>@Embeddable</b> //for value object it is not is an entity object. Value object means does not have real meaning for self individually.<br />
public class Address<br />
{<br />
<b>@Column(name=&#8221;STREET_NAME&#8221;)</b><br />
private String street;<br />
<b>@Column(name=&#8221;CITY_NAME&#8221;)</b><br />
private String city;<br />
<b> @Column(name=&#8221;STATE_NAME&#8221;)</b><br />
private String state;<br />
<b>@Column(name=&#8221;PIN_CODE&#8221;)</b><br />
private String pincode;</p>
<p>public String getStreet() {<br />
return street;<br />
}<br />
public void setStreet(String street) {<br />
this.street = street;<br />
}<br />
public String getCity() {<br />
return city;<br />
}<br />
public void setCity(String city) {<br />
this.city = city;<br />
}<br />
public String getState() {<br />
return state;<br />
}<br />
public void setState(String state) {<br />
this.state = state;<br />
}<br />
public String getPincode() {<br />
return pincode;<br />
}<br />
public void setPincode(String pincode) {<br />
this.pincode = pincode;<br />
}<br />
public String toString()<br />
{<br />
return &#8221; {Street: &#8220;+street+&#8221; City: &#8220;+city+&#8221; State: &#8220;+state+&#8221; Pincode: &#8220;+pincode+&#8221; }&#8221;;<br />
}<br />
}</p>
</div>
</div>
<p><b>hibernate.cfg.xml </b>will be the same as the previous chapter.<b> </b><br />
<b><br />
</b><br />
<b>HibernateTestDemo.java</b></p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">package com.sdnext.hibernate.tutorial;</p>
<p>import org.hibernate.Session;<br />
import org.hibernate.SessionFactory;<br />
import org.hibernate.cfg.AnnotationConfiguration;</p>
<p>import com.sdnext.hibernate.tutorial.dto.Address;<br />
import com.sdnext.hibernate.tutorial.dto.UserDetails;</p>
<p>public class HibernateTestDemo {</p>
<p>/**<br />
* @param args<br />
*/<br />
public static void main(String[] args)<br />
{<br />
UserDetails user = new UserDetails();//Create user object<br />
user.setUserName(&#8220;Dinesh Rajput&#8221;); //Set user name</p>
<p>Address address1 = new Address(); // create first embedded object address<br />
address1.setStreet(&#8220;First Street&#8221;);<br />
address1.setCity(&#8220;First City&#8221;);<br />
address1.setState(&#8220;First State&#8221;);<br />
address1.setPincode(&#8220;First Pin&#8221;);</p>
<p>Address address2 = new Address(); // create second embedded object address<br />
address2.setStreet(&#8220;Second Street&#8221;);<br />
address2.setCity(&#8220;Second City&#8221;);<br />
address2.setState(&#8220;Second State&#8221;);<br />
address2.setPincode(&#8220;Second Pin&#8221;);<br />
//adding addresses object to the list of address<br />
user.getLisOfAddresses().add(address1);<br />
user.getLisOfAddresses().add(address2);</p>
<p>SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //create session factory object<br />
Session session = sessionFactory.openSession(); //create session object from the session factory<br />
session.beginTransaction(); //initialize the transaction object from session<br />
session.save(user); // save the user<br />
session.getTransaction().commit(); //commit the transaction<br />
session.close(); //closing session<br />
}<br />
}</p>
<p><b>Output:</b><br />
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).<br />
log4j:WARN Please initialize the log4j system properly.<br />
Hibernate: insert into TBL_USER_DETAILS (USER_NAME) values (?)<br />
Hibernate: insert into TBL_USER_DETAILS_lisOfAddresses (TBL_USER_DETAILS_USER_ID, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)<br />
Hibernate: insert into TBL_USER_DETAILS_lisOfAddresses (TBL_USER_DETAILS_USER_ID, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)</p>
</div>
</div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/04/outputAddress.jpg" width="640" height="74" border="0" /></div>
<div style="color: #0c343d;">Look carefully to the output line, there are two tables here in the database, first for the UserDetails entity &#8220;<b>TBL_USER_DETAILS</b>&#8221; and second for the embeddable object Address name is &#8220;<b>TBL_USER_DETAILS_lisOfAddresses </b>&#8221; (this is default name of table for address Entity Table Name_field name of the list of the embeddable object in the entity class).</div>
<div style="color: #0c343d;"></div>
<div style="color: #0c343d;">Here see that there is one table for the address object created separately for the collection.</div>
<div style="color: #0c343d;">1. First Table <b>TBL_USER_DETAILS</b></div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/04/tableAddress.jpg" border="0" /></div>
<div class="separator" style="clear: both; text-align: center;"></div>
<div style="color: #0c343d;"> 2. Second Table <b>TBL_USER_DETAILS_lisOfAddresses </b></div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/04/tableAddress2.jpg" border="0" /></div>
<p>In the second table first column, <b style="color: #0c343d;">TBL_USERS_DETAILS_USER_ID</b> has the <b style="color: #0c343d;">user id is</b> foreign key for this table and primary key of the <b style="color: #0c343d;">TBL_USER_DETAILS </b>table.</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/04/tableAddress2-1.jpg" border="0" /></div>
<p><b><br />
</b> <b>In </b><a href="https://dineshonjava.com/p/configuring-collections-and-adding-keys.html">Next Chapter</a>, you will learn more about the <a href="https://dineshonjava.com/p/configuring-collections-and-adding-keys.html">configuration of the collection and adding keys</a>.</p>
<p><b><;<;<a href="https://dineshonjava.com/p/value-types-and-embedding-objects.html">Previous Chapter 13</a><;<; >;>;N<a href="https://dineshonjava.com/p/configuring-collections-and-adding-keys.html">ext Chapter15</a></b></p>
</div>

View Comments
good
hi dinesh there is a probleme while running above programm or query it shows error @EmbeddedCollection please tell me why it occurs or which type of plugnin i have to use
Hi Aryan,
Please provide error log which error is coming.
Thanks,
Dinesh
Hi Dinesh
I got an error when i run this prog and error is ............
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]
Hi Dinesh
I got same error as mentioned above :
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.Property.isValid(Property.java:185)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:440)
at org.hibernate.mapping.RootClass.validate(RootClass.java:192)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1102)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1287)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at pack.TestDemo.main(TestDemo.java:35)
Please help me out to resolve this
You did problem in mapping.
Hi Dinesh, I have the exact same problem and I can't figure out what mistake I am doing in mapping. Can you please elaborate?
Nice article!!!
HI i faced the same problem org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns:
But i fixed this by adding @OneToMany annotations on addressList field
Hi too got Mapping Exception as others and it got fixed by adding @OneToMany annotations as suggested by asad .Thank you
Thank you it helped me to solve issue
hello Sir,
I wanted to save list of entity in single DB connection.
how can i do ?
tx in advance
In this example, I am using a single connection.