<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<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-many-mapping-tutorial.html">the previous tutorial, </a>we look that what is One to Many Mapping and also discussed some examples about that.</p>
<p>In this tutorial of Many to one mapping in hibernate we will discuss about the Many To One Relationship Mapping. Actually Many To One is the reverse of the One To Many(USER has many Vehicles means one user related to the many vehicles in reverse we can say that many vehicles related to the one user i.e. Many To One relationship mapping).</p>
</div>
<div style="color: #20124d;">
<div id="ads-id" align="center"></div>
</div>
<div style="color: #20124d;">
<h2><b>Many-to-One Relationships</b></h2>
<p>A many-to-one relationship is where one entity contains values that refer to another entity (a column or set of columns) that has unique values. In relational databases, these many-to-one relationships are often enforced by foreign key/primary key relationships, and the relationships typically are between fact and dimension tables and between levels in a hierarchy.</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;">
<p><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 class="separator" style="clear: both; text-align: center;"><img src="https://i1.wp.com/dineshonjava.com/wp-content/uploads/2017/04/many-to-one.jpg" border="0" /></div>
</div>
</div>
<p>In this example, multiple vehicles (BMW Car, AUDI Car, Maruti Car and Mahindra etc.) are linked to the same User (whose primary key is 1).</p>
<div style="color: #20124d;">
<p>Class diagram for that is given below.</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://i1.wp.com/dineshonjava.com/wp-content/uploads/2017/04/many-to-one1.jpg" border="0" /></div>
</div>
</div>
<p>According to the relationship, many vehicles can have the same owner.</p>
<div style="color: #20124d;">
<p>To create this relationship you need to have a <i>USER</i> and <i>VEHICLE</i> table. The relational model is shown below.</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/many-to-one2.jpg" border="0" /></div>
<p>For that, we will use the following annotation.<br />
<b>@ManyToOne</b> :<br />
<b>Target:</b><br />
Fields (including property get methods)Defines a single-valued association to another entity class that has many-to-one multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, the non-owning <b>OneToMany </b>entity side must use the mappedBy<b> </b>element to specify the relationship field or property of the entity that is the owner of the relationship. The <b>ManyToOne</b> annotation may be used within an embeddable class to specify a relationship from the embeddable class to an entity class. If the relationship is bidirectional, the non-owning <b>OneToMany </b>entity side must use the <b>mappedBy </b>element of the <b>OneToMany </b>annotation to specify the relationship field or property of the embeddable field or property on the owning side of the relationship. The dot (&#8220;.&#8221;) notation syntax must be used in the <b>mappedBy </b>element to indicate the relationship attribute within the embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.</p>
</div>
</div>
<p>Now we look the following Example related to the <b>One to Many</b> mapping.</p>
<p><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 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;USER&#8221;)</b><br />
public class UserDetails<br />
{<br />
<b>@Id</b><b><br style="color: #20124d;" /> @Column(name=&#8221;USER_ID&#8221;)<br style="color: #20124d;" /> @GeneratedValue(strategy=GenerationType.AUTO)</b><br />
private int userId;</p>
<p><b> @Column(name=&#8221;USER_NAME&#8221;) </b><br />
private String userName;<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 />
}</p>
</div>
</div>
<p><b>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.JoinColumn;<br />
import javax.persistence.ManyToOne;<br />
import javax.persistence.Table;</p>
<p><b>@Entity<br />
@Table(name=&#8221;VEHICLE&#8221;)</b><br />
public class Vehicle<br />
{<br />
<b>@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><b style="color: blue;">@ManyToOne<br />
@JoinColumn(name =&#8221;USER_ID&#8221;)</b><br />
private UserDetails user;</p>
<p>public UserDetails getUser() {<br />
return user;<br />
}<br />
public void setUser(UserDetails user) {<br />
this.user = user;<br />
}<br />
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>
</div>
<p><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>
</div>
<p><b>HibernateTestDemo.java</b></p>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<p>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.UserDetails;<br />
import com.sdnext.hibernate.tutorial.dto.Vehicle;</p>
<p>public class HibernateTestDemo {<br />
/**<br />
* @param args<br />
*/<br />
public static void main(String[] args)<br />
{<br />
UserDetails user = new UserDetails(); //create an user entity</p>
<p>Vehicle vehicle = new Vehicle(); //create a vehicle entity<br />
Vehicle vehicle2 = new Vehicle(); //create second vehicle entity</p>
<p>vehicle.setVehicleName(&#8220;BMW Car&#8221;); //set BMW car<br />
vehicle.setUser(user); //set user for that car</p>
<p>vehicle2.setVehicleName(&#8220;AUDI Car&#8221;); //set second car Audi<br />
vehicle2.setUser(user);//set user for that car</p>
<p>user.setUserName(&#8220;Dinesh Rajput&#8221;); //set user property</p>
<p>SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //create the session factory object<br />
Session session = sessionFactory.openSession(); //create the session object<br />
session.beginTransaction(); //create the transaction object<br />
session.save(vehicle);<br />
session.save(vehicle2);<br />
session.save(user);<br />
session.getTransaction().commit();<br />
session.close();<br />
}<br />
}<br />
******************************************************************************<br />
<b>OUTPUT:</b><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 VEHICLE (USER_ID, VEHICLE_NAME) values (?, ?)<br />
Hibernate: insert into VEHICLE (USER_ID, VEHICLE_NAME) values (?, ?)<br />
Hibernate: insert into USER (USER_NAME) values (?)<br />
Hibernate: update VEHICLE set USER_ID=?, VEHICLE_NAME=? where VEHICLE_ID=?<br />
Hibernate: update VEHICLE set USER_ID=?, VEHICLE_NAME=? where VEHICLE_ID=?<b> </b></p>
</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/many-to-one2-output.jpg" border="0" /></div>
<p>Now we look at 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/many-to-one3-output.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>
<div style="color: purple;">For user class.<br />
<b>UserDetails.hbm.xml</b></div>
<div style="background-color: #ff99cc; border-width: 1px; color: purple;"><;?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;>;<br />
<br style="color: #073763;" /><;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>;<br />
<br style="color: #073763;" /> <;property name=&#8221;userName&#8221;>;<br />
<;column name=&#8221;UserName&#8221; />;<br />
<;/property>;<br />
<;/class>;<br />
<;/hibernate-mapping>;</div>
<div style="color: purple;"></div>
<div style="color: purple;"></div>
<div style="color: purple;">Mapping File For Vehicle Class&#8230;<br />
<b>vehicle.hbm.xml</b></div>
<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>;</p>
</div>
<div style="background-color: #ff99cc; border-width: 1px; color: #20124d;"> <b> <;many-to-one name=&#8221;userDetail&#8221; class=&#8221;com.sdnext.hibernate.tutorial.dto.UserDetails&#8221; column=&#8221;USER_ID&#8221; cascade=&#8221;all&#8221; not-null=&#8221;true&#8221; />;</b><br />
<;/class>;<br />
<;/hibernate-mapping>;</div>
<div style="color: purple;"></div>
<div style="color: purple;">The <i>many-to-one</i> element is used to create the many-to-one relationship between the Vehicle and UserDetail entities. The <i>cascade</i> option is used to cascade the required operations to the associated entity. If the <i>cascade</i> option is set to all then all the operations will be cascaded. For instance, when you save a <i>Vehicle </i>object, the associated UserDetail object will also be saved automatically. <b></b></div>
<div style="color: purple;"><b> </b></div>
<div style="color: purple;">
<p><b>In <a style="color: #20124d;" href="https://dineshonjava.com/p/hibernate-many-to-many-mapping-tutorial.html">Next Chapter</a>, we will discuss the <a style="color: #20124d;" href="https://dineshonjava.com/p/hibernate-many-to-many-mapping-tutorial.html">Many To Many 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-many-mapping-tutorial.html">Previous Chapter 18</a><;<; >;>;N<a style="font-family: Times, 'Times New Roman', serif;" href="https://dineshonjava.com/p/hibernate-many-to-many-mapping-tutorial.html">ext Chapter20>;>;</a></b></p>
</div>
</div>

View Comments
Hi Dinesh,
I am getting below error. Please help.
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.sdnext.hibernate.tutorial.dto.Vehicle]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2108)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2588)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at com.sdnext.hibernate.tutorial.HibernateTestDemo.main(HibernateTestDemo.java:30)
Caused by: java.sql.SQLException: null, message from server: "Unknown column 'USER_ID' in 'field list'"
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1876)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1098)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1192)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2051)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1680)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1527)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
... 16 more
Please check your mapping, it is problem due to primary key generation, please change according to your database.
Even I got the same error, Please help
hello sir... I'm BCA student keval mehta, currently I'm working on a project named Advertisement Foundary at sem 6... We're completing our project in JAVA... We're unable to complete the coding via hibernate.... So, that we need your help... We all are from Ahmedabad, Gujarat... If possible to you; can you please give us your contact details??!!!
Why are you put Popular Post in middle of current topic.
Please remove the same.
where should these hibernate.xml file be placed in the project structure
I was delighted with the explanation of the OneToMany and ManyToOne relationships.
I have a similar problem, but despite having followed your explanations goes wrong.
Can you help me ?
If you like to help me understand the problem, you leave my email and in private mail I send you the structure of the tables and the error that is generated in compilation.
thank you
Moreno
I am 65 years old and has always been passionate about programming. I fell in love with java and I find Hibernate fantastic, even though I'm having a problem with these relationships.
Thank you
Moreno
please send me details at admin@dineshonjava.com