<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div style="color: #20124d;">
<p>In <a href="https://dineshonjava.com/p/hibernate-one-to-one-mapping-tutorial.html">previous tutorial</a> we look that what is One To One Mapping and also discussed some examples about that.</p>
<p>In this tutorial of one to many mapping in hibernate example we will discuss about the One To Many Mapping. A one-to-many relationship occurs when one entity is related to many occurrences in another entity.</p>
</div>
<div style="color: #20124d;">
<div id="ads-id" align="center"></div>
</div>
<div style="color: #20124d;">In this chapter you will learn how to map one-to-many relationship using Hibernate. Consider the following relationship between <b><i>UserDetails</i></b> Class and <b><i>Vehicle</i> </b>entity.</div>
<div style="color: #20124d;"></div>
<div style="color: #20124d;">One user have the multiple vehicles.</div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://i1.wp.com/dineshonjava.com/wp-content/uploads/2017/04/one-to-many.jpg" border="0" /></div>
<div style="background-color: #f2f9fc; border:1px solid #c9e6f2;border-radius:3px;padding:16px;line-height:1.45;">
<span style="color: red;font-size: x-large;text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<div style="color: #20124d;">Class diagram for that given below.</div>
<p> ;</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://i1.wp.com/dineshonjava.com/wp-content/uploads/2017/04/one-to-many1.png" border="0" /></div>
<div class="separator" style="clear: both; text-align: center;"></div>
<div style="color: #20124d;">In this example <b>UserDetails </b>class has the collection of the another entity class <b>Vehicle</b>. So the given below diagram so table structure for that.</div>
<p> ;</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://i1.wp.com/dineshonjava.com/wp-content/uploads/2017/04/one-to-many-table.jpg" border="0" /></div>
<div style="color: #20124d;"></div>
<div style="color: #20124d;">For that we will use the following annotation.</div>
<div style="color: orange;"><b>@OneToMany:</b></div>
<p><b>Target:</b><br />
Fields (including property get methods)Defines a many-valued association with one-to-many multiplicity. If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified. If the relationship is bidirectional, the<b> mappedBy </b>element must be used to specify the relationship field or property of the entity that is the owner of the relationship. The <b style="color: #20124d;">OneToMany </b>annotation may be used within an <b style="color: #20124d;">embeddable </b>class contained within an entity class to specify a relationship to a collection of entities. If the relationship is bidirectional, the <b>mappedBy</b><b style="color: #20124d;"> </b>element must be used to specify the relationship field or property of the entity that is the owner of the relationship.</p>
</div>
<p>Now we look the following Example related to the <b>One to Many</b> mapping.</p>
<p>1. First Create Vehicle Class<br />
<b style="color: purple;">Vehicle.java</b></p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<p>package com.sdnext.hibernate.tutorial.dto;</p>
<p>import javax.persistence.Column;<br />
import javax.persistence.Entity;<br />
import javax.persistence.GeneratedValue;<br />
import javax.persistence.GenerationType;<br />
import javax.persistence.Id;<br />
import javax.persistence.Table;</p>
<p><b>@Entity<br style="color: #20124d;" />@Table(name=&#8221;VEHICLE&#8221;)</b><br />
public class Vehicle<br />
{<br />
<b style="color: #20124d;">@Id<br />
@GeneratedValue(strategy=GenerationType.AUTO)<br />
@Column(name=&#8221;VEHICLE_ID&#8221;)</b><br />
private int vehicleId;</p>
<p><b> @Column(name=&#8221;VEHICLE_NAME&#8221;)</b><br />
private String vehicleName;</p>
<p>public int getVehicleId() {<br />
return vehicleId;<br />
}<br />
public void setVehicleId(int vehicleId) {<br />
this.vehicleId = vehicleId;<br />
}<br />
public String getVehicleName() {<br />
return vehicleName;<br />
}<br />
public void setVehicleName(String vehicleName) {<br />
this.vehicleName = vehicleName;<br />
}<br />
}</p>
</div>
<p>2. Create the User Class<br />
<b style="color: purple;">UserDetails.java</b></p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<p>package com.sdnext.hibernate.tutorial.dto;</p>
<p>import java.util.ArrayList;<br />
import java.util.Collection;</p>
<p>import javax.persistence.Column;<br />
import javax.persistence.Entity;<br />
import javax.persistence.GeneratedValue;<br />
import javax.persistence.GenerationType;<br />
import javax.persistence.Id;<br />
import javax.persistence.JoinColumn;<br />
import javax.persistence.JoinTable;<br />
import javax.persistence.OneToMany;<br />
import javax.persistence.Table;</p>
<p><b style="color: #20124d;">@Entity<br />
@Table (name=&#8221;USER&#8221;)</b><br />
public class UserDetails<br />
{<br />
<b style="color: #20124d;">@Id<br />
@Column(name=&#8221;USER_ID&#8221;)<br />
@GeneratedValue(strategy=GenerationType.AUTO)</b><br />
private int userId;</p>
<p><b style="color: #20124d;">@Column(name=&#8221;USER_NAME&#8221;) </b><br />
private String userName;</p>
<p><b>@OneToMany<br style="color: blue;" /> @JoinTable( name=&#8221;USER_VEHICLE&#8221;, <br style="color: blue;" /> joinColumns=@JoinColumn(name=&#8221;USER_ID&#8221;), <br style="color: blue;" /> inverseJoinColumns=@JoinColumn(name=&#8221;VEHICLE_ID&#8221;))</b> //its optional using for name configuration of the join table<br />
private Collection<;Vehicle>; vehicle = new ArrayList<;Vehicle>;();</p>
<p>public int getUserId() {<br />
return userId;<br />
}<br />
public Collection<;Vehicle>; getVehicle() {<br />
return vehicle;<br />
}<br />
public void setVehicle(Collection<;Vehicle>; vehicle) {<br />
this.vehicle = vehicle;<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 />
}</p>
</div>
<p>3. Create the hibernate configuration file.<br />
<b style="color: purple;">hibernate.cfg.xml</b>:</p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<p><;?xml version=&#8221;1.0&#8243; encoding=&#8221;UTF-8&#8243;?>;</p>
<p><;!DOCTYPE hibernate-configuration PUBLIC<br />
&#8220;-//Hibernate/Hibernate Configuration DTD 3.0//EN&#8221;<br />
&#8220;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&#8221;>;</p>
<p><;hibernate-configuration>;<br />
<;session-factory>;<br />
<;!&#8211; Database connection settings &#8211;>;<br />
<;property name=&#8221;connection.driver_class&#8221;>;com.mysql.jdbc.Driver<;/property>;<br />
<;property name=&#8221;connection.url&#8221;>;jdbc:mysql://localhost:3306/hibernateDB<;/property>;<br />
<;property name=&#8221;connection.username&#8221;>;root<;/property>;<br />
<;property name=&#8221;connection.password&#8221;>;root<;/property>;</p>
<p><;!&#8211; JDBC connection pool (use the built-in) &#8211;>;<br />
<;property name=&#8221;connection.pool_size&#8221;>;1<;/property>;</p>
<p><;!&#8211; SQL dialect &#8211;>;<br />
<;property name=&#8221;dialect&#8221;>;org.hibernate.dialect.MySQLDialect<;/property>;</p>
<p><;!&#8211; Enable Hibernate&#8217;s automatic session context management &#8211;>;<br />
<;property name=&#8221;current_session_context_class&#8221;>;thread<;/property>;</p>
<p><;!&#8211; Disable the second-level cache &#8211;>;<br />
<;property name=&#8221;cache.provider_class&#8221;>;org.hibernate.cache.NoCacheProvider<;/property>;</p>
<p><;!&#8211; Echo all executed SQL to stdout &#8211;>;<br />
<;property name=&#8221;show_sql&#8221;>;true<;/property>;</p>
<p><;!&#8211; Drop and re-create the database schema on startup &#8211;>;<br />
<;property name=&#8221;hbm2ddl.auto&#8221;>;create<;/property>;</p>
<p><;mapping class=&#8221;com.sdnext.hibernate.tutorial.dto.UserDetails&#8221;/>;<br />
<;mapping class=&#8221;com.sdnext.hibernate.tutorial.dto.Vehicle&#8221;/>;</p>
<p><;/session-factory>;<br />
<;/hibernate-configuration>;</p>
</div>
<p>4. Create Test Demo class for run this code.<br />
<b>HibernateTestDemo.java</b></p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<div style="color: purple;">package com.sdnext.hibernate.tutorial;</div>
<div style="color: purple;"></div>
<div style="color: purple;">import org.hibernate.Session;</div>
<div style="color: purple;">import org.hibernate.SessionFactory;</div>
<div style="color: purple;">import org.hibernate.cfg.AnnotationConfiguration;</div>
<div style="color: purple;"></div>
<div style="color: purple;">import com.sdnext.hibernate.tutorial.dto.UserDetails;</div>
<div style="color: purple;">import com.sdnext.hibernate.tutorial.dto.Vehicle;</div>
<div style="color: purple;"></div>
<div style="color: purple;">public class HibernateTestDemo {</div>
<div style="color: purple;"> /**</div>
<div style="color: purple;"> * @param args</div>
<div style="color: purple;"> */</div>
<div style="color: purple;"> public static void main(String[] args)</div>
<div style="color: purple;"> {</div>
<p>UserDetails user = new UserDetails(); //create the user entity object</p>
<p>Vehicle vehicle = new Vehicle(); //create the first vehicle entity object<br />
Vehicle vehicle2 = new Vehicle(); //create the second vehicle entity</p>
<p>vehicle.setVehicleName(&#8220;BMW Car&#8221;); //set the value to the vehicle entity<br />
vehicle2.setVehicleName(&#8220;AUDI Car&#8221;);</p>
<p>user.setUserName(&#8220;Dinesh Rajput&#8221;); //Set the value to the user entity<br />
user.getVehicle().add(vehicle); //add vehicle to the list of the vehicle<br />
user.getVehicle().add(vehicle2);<br style="color: purple;" /> <br style="color: purple;" /> SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //create session factory object<br />
Session session = sessionFactory.openSession(); //create the session object<br />
session.beginTransaction(); //start the transaction of the session object</p>
<p>session.save(vehicle); //saving the vehicle to the database<br />
session.save(vehicle2);<br />
session.save(user); //save the user to the database</p>
<p>session.getTransaction().commit(); //close the transaction<br />
session.close(); //close the session<br />
}<br />
}<br />
******************************************************************************<br />
<b>OUTPUT:</b><br />
******************************************************************************<br />
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).<br style="color: red;" />log4j:WARN Please initialize the log4j system properly.<br />
Hibernate: insert into VEHICLES (VEHICLE_NAME) values (?)<br />
Hibernate: insert into VEHICLES (VEHICLE_NAME) values (?)<br />
Hibernate: insert into USER (USER_NAME) values (?)<br />
Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?)<br />
Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?)</p>
</div>
</div>
<p> ;</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://i1.wp.com/dineshonjava.com/wp-content/uploads/2017/04/output_table.jpg" width="640" height="122" border="0" /></div>
<p>Now we look the table structure about this example.</p>
<div class="separator" style="clear: both; text-align: center;"></div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://i1.wp.com/dineshonjava.com/wp-content/uploads/2017/04/output_tables.jpg" border="0" /></div>
<p>Now how can implement this mapping through mapping file(<b> .hbm.xml</b>) instead of the <b>annotations</b>.</p>
<p>For user class..<br />
<b>UserDetails.hbm.xml</b></p>
<div style="background-color: #ff99cc; border-width: 1px; color: purple;">
<p><;?xml version=&#8221;1.0&#8243;?>;<br />
<;!DOCTYPE hibernate-mapping PUBLIC<br />
&#8220;-//Hibernate/Hibernate Mapping DTD 3.0//EN&#8221;<br />
&#8220;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&#8221;>;</p>
<p><;hibernate-mapping>;<br />
<;class name=&#8221;com.sdnext.hibernate.tutorial.dto.UserDetails&#8221; table=&#8221;USER&#8221;>;<br />
<;id name=&#8221;userId&#8221; type=&#8221;long&#8221; column=&#8221;ID&#8221; >;<br />
<;generator class=&#8221;assigned&#8221;/>;<br />
<;/id>;</p>
<p><;property name=&#8221;userName&#8221;>;<br />
<;column name=&#8221;UserName&#8221; />;<br />
<;/property>;</p>
</div>
<div style="background-color: #ff99cc; border-width: 1px; color: purple;"> <b> <;list name=&#8221;vehicle&#8221; table=&#8221;STUDENT_VEHICLE&#8221; cascade=&#8221;all&#8221;>;<br style="color: blue;" /> <;key column=&#8221;USER_ID&#8221; />;<br style="color: blue;" /> <;many-to-many column=&#8221;VEHICLE_ID&#8221; unique=&#8221;true&#8221; class=&#8221;com.sdnext.hibernate.tutorial.dto.Vehicle&#8221; />;<br style="color: blue;" /><;/list>;</b></div>
<div style="background-color: #ff99cc; border-width: 1px; color: purple;">
<;/class>;<br />
<;/hibernate-mapping>;</div>
<p>Mapping File For Vehicle Class&#8230;<br />
<b>vehicle.hbm.xml</b></p>
<div style="background-color: #ff99cc; border-width: 1px; color: #20124d;">
<p><;?xml version=&#8221;1.0&#8243;?>;<br />
<;!DOCTYPE hibernate-mapping PUBLIC<br />
&#8220;-//Hibernate/Hibernate Mapping DTD 3.0//EN&#8221;<br />
&#8220;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&#8221;>;</p>
<p><;hibernate-mapping>;<br />
<;class name=&#8221;com.sdnext.hibernate.tutorial.dto.Vehicle&#8221; table=&#8221;VEHICLE&#8221;>;<br />
<;id name=&#8221;userId&#8221; type=&#8221;long&#8221; column=&#8221;ID&#8221; >;<br />
<;generator class=&#8221;assigned&#8221;/>;<br />
<;/id>;<br />
<;property name=&#8221;vehicleName&#8221; column=&#8221;VEHICLE_NAME&#8221;>; <;/property>;<br />
<;/class>;<br />
<;/hibernate-mapping>;</p>
</div>
<p>So it is brief description about the One To Many Mapping with using <b>annotation </b>and also using<b> .hbm.xml</b> files for entity class.</p>
<p><b>In <a href="https://dineshonjava.com/p/hibernate-many-to-one-mapping-tutorial.html">Next Chapter</a> we will discuss about the <a href="https://dineshonjava.com/p/hibernate-many-to-one-mapping-tutorial.html">Many To One Mapping</a>.</b><br />
<b><br />
</b> <b> <;<;<a style="font-family: Times, 'Times New Roman', serif;" href="https://dineshonjava.com/p/hibernate-one-to-one-mapping-tutorial.html">Previous Chapter 17</a><;<; >;>;N<a style="font-family: Times, 'Times New Roman', serif;" href="https://dineshonjava.com/p/hibernate-many-to-one-mapping-tutorial.html">ext Chapter19</a>>;>;</b></p>
<p> ;</p>
</div>

View Comments
source code?