Many To One Mapping in JPA

So far we have discussed the  various mapping schemes like One To One , One To Many and Many To Many . In this chapter we are discussing the Many To One Mapping in JPA.Like the previous chapter ,  we are using  OpenJPA as JPA  provider implementation.Also we are using the same database and workspace set up we made earlier.So we will be using the ‘jpasampledb’  database we created there.

Many To One Mapping in JPA

In case of a Many To One relation , there are parent objects and children objects.Each parent object will be having a child object.A child object can be the child object of any number of parent objects.So many parent objects will be having relation with one  child object  . The Bidirectional relation is also possible here. In case of   Many To One , the inverse relation would be One To Many .

Now let us consider a typical example to illustrate the Many to One mapping. Consider the relation between  a Phone entity and a User entity. Suppose each Phone object is  mapped  to a User object.A User can have any number of Phone objects. So each Phone object will be mapped to a User object. Any number of Phone objects can be mapped to the same User object.

Queries for Creating Database tables

Let us create two tables USEDETAILS_TABLE and PHONEDETAILS_TABLE.The PHONEDETAILS_TABLE should have a foreign key to refer to the USERDETAILS_TABLE. The USER_ID from the USERDETAILS_TABLE is using as the foreign key in PHONEDETAILS_TABLE

(Alternately we can create intermediate table for doing the mapping)

persistence.xml

org.apache.openjpa.persistence.PersistenceProviderImpl com.jpa.many2one.entities.User
com.jpa.many2one.entities.Phone

Phone.java

import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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(name = "Phone")
@Table(name = "PHONEDETAILS_TABLE")
public class Phone implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;

private int phoneid;
private String phoneNumber;
private String phoneType;
private User userDetails;

public Phone() {

}

public Phone(String phoneNumber, String phoneType, User user) {
this.phoneNumber = phoneNumber;
this.phoneType = phoneType;
this.userDetails = user;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PHONE_ID")
public int getPhoneid() {
return phoneid;
}

public void setPhoneid(int phoneid) {
this.phoneid = phoneid;
}

@Column(name = "PHONE_NUMBER")
public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

@Column(name = "PHONE_TYPE")
public String getPhoneType() {
return phoneType;
}

public void setPhoneType(String phoneType) {
this.phoneType = phoneType;
}

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "USER_ID", nullable = false)
public User getUserDetails() {
return userDetails;
}

public void setUserDetails(User userDetails) {
this.userDetails = userDetails;
}

public String toString() {
return " [ Phone Id : " + getPhoneid() + " ; Phone Number : "
+ getPhoneNumber() + " ; Phone Type : " + getPhoneType()
+ " ; User Details : " + getUserDetails() + " ] ";
}

}

User.java

import java.io.Serializable;
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(name = "User")
@Table(name = "USERDETAILS_TABLE")
public class User implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private int userId;
private String userName;
private String countryName;
private String stateName;

public User() {

}

public User(String userName, String countryName, String stateName) {
this.userName = userName;
this.countryName = countryName;
this.stateName = stateName;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

@Column(name = "USER_NAME")
public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

@Column(name = "COUNTRY_NAME")
public String getCountryName() {
return countryName;
}

public void setCountryName(String countryName) {
this.countryName = countryName;
}

@Column(name = "STATE_NAME")
public String getStateName() {
return stateName;
}

public void setStateName(String stateName) {
this.stateName = stateName;
}

public String toString() {
return "[ User Id : " + getUserId() + " ; User Name : " + getUserName()
+ " ; State Name : " + getStateName() + " ; Country Name : "
+ getCountryName() + " ]";
}

}

Many2OneSample.java

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.jpa.many2one.entities.Phone;
import com.jpa.many2one.entities.User;

public class Many2OneSample {

public Many2OneSample() {

}

public void insertRecords() {
User user1 = new User("Bijoy", "India", "Kerala");
Phone phone1 = new Phone("09xxxxxxxxx", "Mobile", user1);
Phone phone2 = new Phone("04xxxxxxxxx", "LandLine", user1);
User user2 = new User("Karthik", "India", "Tamil Nadu");
Phone phone3 = new Phone("08xxxxxxxxx", "Mobile", user2);
Phone phone4 = new Phone("02xxxxxxxxx", "LandLine", user2);
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("OpenJPASample");
EntityManager entitymanager = entityManagerFactory
.createEntityManager();
if (null != entitymanager) {
EntityTransaction transaction = entitymanager.getTransaction();
transaction.begin();
entitymanager.persist(phone1);
entitymanager.persist(phone2);
entitymanager.persist(phone3);
entitymanager.persist(phone4);
transaction.commit();
System.out.println("Phone records inserted to database..");

}
}

public void fetchRecods() {
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("OpenJPASample");
EntityManager entitymanager = entityManagerFactory
.createEntityManager();
if (null != entitymanager) {
EntityTransaction readTransaction = entitymanager.getTransaction();
readTransaction.begin();
Query query = entitymanager
.createQuery("select phone FROM Phone phone");
List list = query.getResultList();
Iterator iterator = list.iterator();
System.out.println("Phone Details fetched from database : ");
while (iterator.hasNext()) {
Phone phone = (Phone) iterator.next();
System.out.println(phone);
}

readTransaction.commit();
System.out.println("Phone Details over");
}

}

public static void main(String[] args) {
Many2OneSample sample = new Many2OneSample();
sample.insertRecords();
sample.fetchRecods();
}

}

Output

Phone records inserted to database..

Phone Details fetched from database :

 [ Phone Id : 5051 ; Phone Number : 09xxxxxxxxx ; Phone Type : Mobile ; User Details : [ User Id : 5101 ; User Name : Bijoy ; State Name : Kerala ; Country Name : India  ] ]

 [ Phone Id : 5052 ; Phone Number : 04xxxxxxxxx ; Phone Type : LandLine ; User Details : [ User Id : 5101 ; User Name : Bijoy ; State Name : Kerala ; Country Name : India  ] ]

 [ Phone Id : 5053 ; Phone Number : 08xxxxxxxxx ; Phone Type : Mobile ; User Details : [ User Id : 5102 ; User Name : Karthik ; State Name : Tamil Nadu ; Country Name : India  ] ]

 [ Phone Id : 5054 ; Phone Number : 02xxxxxxxxx ; Phone Type : LandLine ; User Details : [ User Id : 5102 ; User Name : Karthik ; State Name : Tamil Nadu ; Country Name : India  ] ]

Phone Details over

In this  case ,  Phone objects with ids 5051 and 5052 are related to a single User object(With id value 5101). Also  other two Phone objects are related to the second User object(With id value 5102). So clearly the relation is a Many To One relation

See Related Topics:

JPA Overview

JPA Example – Insert/Read

find method in JPA example

JPA Update Example

JPA Delete EXample

JPQL

JPQL Update Query Example

JPQL Delete Query

Caching

Overview to caching in JPA

Locking in JPA

Data  Locking in JPA

JPA Mapping Schemes

One To One Mapping in JPA

One To Many mapping in JPA

Many To Many Mapping in JPA

Leave a Reply

Your email address will not be published. Required fields are marked *