Many to One Mapping in Hibernate Example

In the previous tutorial, we look that what is One to Many Mapping and also discussed some examples about that.

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).

Many-to-One Relationships

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.

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).

Class diagram for that is given below.

According to the relationship, many vehicles can have the same owner.

To create this relationship you need to have a USER and VEHICLE table. The relational model is shown below.

For that, we will use the following annotation.
@ManyToOne :
Target:
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 OneToMany entity side must use the mappedBy element to specify the relationship field or property of the entity that is the owner of the relationship.  The ManyToOne 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 OneToMany entity side must use the mappedBy element of the OneToMany annotation to specify the relationship field or property of the embeddable field or property on the owning side of the relationship. The dot (“.”) notation syntax must be used in the mappedBy 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.

Now we look the following Example related to the One to Many mapping.

UserDetails.java

package com.sdnext.hibernate.tutorial.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name=”USER”)

public class UserDetails
{
@Id
    @Column(name=”USER_ID”)
    @GeneratedValue(strategy=GenerationType.AUTO)

private int    userId;

  @Column(name=”USER_NAME”)
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}

Vehicle.java

package com.sdnext.hibernate.tutorial.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name=”VEHICLE”)

public class Vehicle
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name=”VEHICLE_ID”)

private int vehicleId;

@Column(name=”VEHICLE_NAME”)
private String vehicleName;

@ManyToOne
@JoinColumn(name =”USER_ID”)

private UserDetails user;

public UserDetails getUser() {
return user;
}
public void setUser(UserDetails user) {
this.user = user;
}
public int getVehicleId() {
return vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
}

hibernate.cfg.xml:

<?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>
<!– Database connection settings –>
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”connection.url”>jdbc:mysql://localhost:3306/hibernateDB</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”>1</property>

<!– SQL dialect –>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

<!– Enable Hibernate’s automatic session context management –>
<property name=”current_session_context_class”>thread</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>

<!– Drop and re-create the database schema on startup –>
<property name=”hbm2ddl.auto”>create</property>

<mapping class=”com.sdnext.hibernate.tutorial.dto.UserDetails”/>
<mapping class=”com.sdnext.hibernate.tutorial.dto.Vehicle”/>

</session-factory>
</hibernate-configuration>

HibernateTestDemo.java

package com.sdnext.hibernate.tutorial;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.sdnext.hibernate.tutorial.dto.UserDetails;
import com.sdnext.hibernate.tutorial.dto.Vehicle;

public class HibernateTestDemo {
/**
* @param args
*/
public static void main(String[] args)
{
UserDetails user = new UserDetails(); //create an user entity

Vehicle vehicle = new Vehicle(); //create a vehicle entity
Vehicle vehicle2 = new Vehicle(); //create second vehicle entity

vehicle.setVehicleName(“BMW Car”); //set BMW car
vehicle.setUser(user); //set user for that car

vehicle2.setVehicleName(“AUDI Car”); //set second car Audi
vehicle2.setUser(user);//set user for that car

user.setUserName(“Dinesh Rajput”); //set user property

SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //create the session factory object
Session session = sessionFactory.openSession(); //create the session object
session.beginTransaction(); //create the transaction object
session.save(vehicle);
session.save(vehicle2);
session.save(user);
session.getTransaction().commit();
session.close();
}
}
******************************************************************************
OUTPUT:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into VEHICLE (USER_ID, VEHICLE_NAME) values (?, ?)
Hibernate: insert into VEHICLE (USER_ID, VEHICLE_NAME) values (?, ?)
Hibernate: insert into USER (USER_NAME) values (?)
Hibernate: update VEHICLE set USER_ID=?, VEHICLE_NAME=? where VEHICLE_ID=?
Hibernate: update VEHICLE set USER_ID=?, VEHICLE_NAME=? where VEHICLE_ID=? 

 

Now we look at the table structure about this example.

Now how can implement this mapping through mapping file( .hbm.xml) instead of the annotations?

For user class.
UserDetails.hbm.xml
<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>

<hibernate-mapping>
<class name=”com.sdnext.hibernate.tutorial.dto.UserDetails” table=”USER”>
<id name=”userId” type=”long” column=”ID” >
<generator class=”assigned”/>
</id>

    <property name=”userName”>
<column name=”UserName” />
</property>
</class>
</hibernate-mapping>
Mapping File For Vehicle  Class…
vehicle.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>

<hibernate-mapping>
<class name=”com.sdnext.hibernate.tutorial.dto.Vehicle” table=”VEHICLE”>
<id name=”userId” type=”long” column=”ID” >
<generator class=”assigned”/>
</id>
<property name=”vehicleName” column=”VEHICLE_NAME”>  </property>

   <many-to-one name=”userDetail” class=”com.sdnext.hibernate.tutorial.dto.UserDetails” column=”USER_ID” cascade=”all” not-null=”true” />
</class>
</hibernate-mapping>
The many-to-one element is used to create the many-to-one relationship between the Vehicle and UserDetail entities. The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to all then all the operations will be cascaded. For instance, when you save a Vehicle object, the associated UserDetail object will also be saved automatically. 
 

In Next Chapter, we will discuss the Many To Many Mapping.

                <<Previous Chapter 18<<    >>Next Chapter20>>

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.

  • 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??!!!

  • 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