jpa

JPA mappedBy Example

Hello readers, in this tutorial, we will show how to implement the mappedBy annotation in JPA using EclipseLink and MySQL in Java.
 
 
 
 
 
 
 
 
 
 

1. Introduction

Java Persistence API (JPA), is a standard interface which wraps the different Object Relational Mapping (ORM) tools such as Hibernate, EclipseLink, OpenJPA etc. JPA provides a javax.persistence.EntityManager interface which is used to interact with the database. The instance of EntityManager plays around the persistence context and the EntityManagerFactory interacts with the EntityManager object.

  • Persistence Context is the set of entity instances where for any persistence entity identity, there is a unique entity instance. The lifecycle of entity instances is managed within the persistence context using the EntityManager. We can detach and merge the entity instances within a persistence context
  • Entity Manager is a model borrowed from the traditional JDBC frameworks i.e. making it easier for the developers to perform the basic database operations with a very little code

In this standalone JPA example, we are using EclipseLink with MySQL Database. EclipseLink is a popular open source ORM (Object Relation Mapping) tool for Java platform used for mapping an entity to a traditional relational database like Oracle, MySQL etc.

1.1 JPA Benefits

There are many advantages of using the JPA framework, for e.g.

  • The benefit of using the JPA framework over any specific Object Relational Model (ORM) related libraries like Hibernate, iBatis etc. is that developers do not change the code when they change the vendor
  • The code is loosely coupled with the underlying ORM framework
  • Improves data security and data access to the users by using host and query languages
  • Improves application performance by reducing the data redundancy
  • Greater data integrity and independence of applications programs
  • Provides simple querying of data

1.2 How it can be achieved?

Programmers can achieve persistence in their application by introducing the persistence.xml in their code, which has to be located in the META-INF directory in the project classpath. One persistence.xml file can include definitions for one or more persistence units. This file plays a crucial role in the concept of JPA as in this configuration file, developers will register the database and specify the entity class. Let’s take a look and understand the sample code.

Sample persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
	xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="TestPersistence" transaction-type="RESOURCE_LOCAL">
		<class><!-- Entity Manager Class Name --></class>
		<properties>
			<property name="javax.persistence.jdbc.driver" value="Database Driver Name" />
			<property name="javax.persistence.jdbc.url" value="Database Url" />
			<property name="javax.persistence.jdbc.user" value="Database Username" />
			<property name="javax.persistence.jdbc.password" value="Database Password" />
		</properties>
	</persistence-unit>
</persistence>

The persistence.xml file indicates that there is only one Persistence Unit mapped with the name TestPersistence and the transaction type for this Persistence Unit is RESOURCE_LOCAL. There are two types of transactions:

  • JTA
  • RESOURCE_LOCAL

If developers select the RESOURCE_LOCAL, then the transaction will be managed by the JPA Provider Implementation in use. If JTA is specified, then the transactions will be managed by the Application Server.

Do remember, if a developer only wants to have JPA transactions, then RESOURCE_LOCAL is a good choice. But, if a developer would like the transactions to contain resources other than JPA, like EJBs, JMS then JTA is the correct choice.

1.3 Download & Install EclipseLink

You can watch this video in order to download and install the JPA in Eclipse via the EclipseLink.

1.4 Download & Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows Operating system.

Now, open up the Eclipse Ide and let’s see how to implement the mappedBy annotation in JPA framework.

2. Java mappedBy Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application’s Project Structure
Fig. 1: Application’s Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on finish and the creation of a maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JPAMappedbyExample</groupId>
	<artifactId>JPAMappedbyExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

We can start adding the dependencies that developers want like Eclipse Link, MySQL Connector Jar, and Hibernate etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called jpaMappedBy with tables: EMPLOYEE_TABLE and PASSPORT_TABLE. Open the MySQL or the workbench terminal and execute the SQL script:

DROP DATABASE IF EXISTS jpaMappedBy;
  
CREATE DATABASE IF NOT EXISTS jpaMappedBy;

USE jpaMappedBy;

CREATE TABLE EMPLOYEE_TABLE(
  EMP_ID INT NOT NULL auto_increment, 
  EMP_NAME VARCHAR(50) NOT NULL, 
  PASSPORT_NUMBER INT NOT NULL, 
  PRIMARY KEY (EMP_ID)
);

CREATE TABLE PASSPORT_TABLE(
  PASSPORT_NUMBER INT NOT NULL auto_increment, 
  ADDRESS_LINE1 VARCHAR(100) NOT NULL, 
  ADDRESS_LINE2 VARCHAR(100) NOT NULL, 
  STATE_NAME VARCHAR(50) NOT NULL, 
  COUNTRY_NAME VARCHAR(50) NOT NULL, 
  PRIMARY KEY (PASSPORT_NUMBER)
);

DESC EMPLOYEE_TABLE;

DESC PASSPORT_TABLE;

If everything goes well, the database and the table will be shown in the MySQL Workbench.

Fig. 5: Database & Table Creation
Fig. 5: Database & Table Creation

3.2 Maven Dependencies

In this example, we are using the stable Hibernate, MySQL, and Eclipse Link version in order to support the JPA Content and make a successful database connection. The rest dependencies will be automatically resolved by Maven and the updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JPAMappedbyExample</groupId>
	<artifactId>JPAMappedbyExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink -->
		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>eclipselink</artifactId>
			<version>2.5.2</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>javax.persistence</artifactId>
			<version>2.0.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.40</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.11.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>5.2.11.Final</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.3 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 6: Java Package Creation
Fig. 6: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.jpa.mappedBy.

Fig. 7: Java Package Name (com.jcg.jpa.mappedBy)
Fig. 7: Java Package Name (com.jcg.jpa.mappedBy)

Once the package is created, we will need to create the model and the implementation classes. Right-click on the newly created package, New -> Class.

Fig. 8: Java Class Creation
Fig. 8: Java Class Creation

A new pop window will open and enter the file name as: Employee. The model class will be created inside the package: com.jcg.jpa.mappedBy.

Fig. 9: Java Class (Employee.java)
Fig. 9: Java Class (Employee.java)

Repeat the step (i.e. Fig. 8) and enter the filename as: Passport. The entity model class will be created inside the package: com.jcg.jpa.mappedBy.

Fig 10: Java Class (Passport.java)
Fig 10: Java Class (Passport.java)

Again, repeat the step listed in Fig. 8 and enter the file name as AppDemo. The implementation class will be created inside the package: com.jcg.jpa.mappedBy.

Fig. 11: Java Class (AppDemo.java)
Fig. 11: Java Class (AppDemo.java)

3.3.1 Implementation of Model Class

Add the following code to it:

Employee.java

package com.jcg.jpa.mappedBy;

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.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "EMPLOYEE_TABLE")
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "EMP_ID")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int employeeId;

	@Column(name = "EMP_NAME")
	private String name;

	@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
	@JoinColumn(name = "PASSPORT_NUMBER")
	private Passport passportDetails;

	public Employee() { }

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Passport getPassportDetails() {
		return passportDetails;
	}

	public void setPassportDetails(Passport passportDetails) {
		this.passportDetails = passportDetails;
	}
}

3.3.2 Implementation of Entity Model Class

Add the following code to it:

Passport.java

package com.jcg.jpa.mappedBy;

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
@Table(name = "PASSPORT_TABLE")
public class Passport implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "PASSPORT_NUMBER")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int passportNumber;

	@Column(name = "ADDRESS_LINE1")
	private String addressLine1;

	@Column(name = "ADDRESS_LINE2")
	private String addressLine2;

	@Column(name = "STATE_NAME")
	private String state;

	@Column(name = "COUNTRY_NAME")
	private String country;

	public Passport() { }

	public int getPassportNumber() {
		return passportNumber;
	}

	public void setPassportNumber(int passportNumber) {
		this.passportNumber = passportNumber;
	}

	public String getAddressLine1() {
		return addressLine1;
	}

	public void setAddressLine1(String addressLine1) {
		this.addressLine1 = addressLine1;
	}

	public String getAddressLine2() {
		return addressLine2;
	}

	public void setAddressLine2(String addressLine2) {
		this.addressLine2 = addressLine2;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}
}

3.3.3 Implementation of Utility Class

This is the service class which implements the Java Persistence API to perform a database transaction (i.e. SQL INSERT Operation). Add the following code to it:

AppDemo.java

package com.jcg.jpa.mappedBy;

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

public class AppDemo {

	private static final EntityManagerFactory emFactoryObj;
	private static final String PERSISTENCE_UNIT_NAME = "JPAMappedbyExample";	

	static {
		emFactoryObj = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	}

	// This Method Is Used To Retrieve The 'EntityManager' Object
	public static EntityManager getEntityManager() {
		return emFactoryObj.createEntityManager();
	}

	private static void insertRecord() {
		EntityManager entityMgrObj = getEntityManager();
		if (null != entityMgrObj) {
			entityMgrObj.getTransaction().begin();

			Employee empObj = new Employee();
			empObj.setName("Harry Potter");

			Passport passportDetailsObj = new Passport();
			passportDetailsObj.setAddressLine1("Cupboard Under D' Stairs");
			passportDetailsObj.setAddressLine2(" 4 Privet Drive");
			passportDetailsObj.setState("Little Whinging");
			passportDetailsObj.setCountry("Surrey");
			empObj.setPassportDetails(passportDetailsObj);
			entityMgrObj.persist(empObj);

			entityMgrObj.getTransaction().commit();

			entityMgrObj.clear();
			System.out.println("Record Successfully Inserted In The Database");
		}
	}

	public static void main(String[] args) {
		insertRecord();
	}
}

3.4 Database Configuration File

Developers can achieve persistence in their application by introducing the persistence.xml in their code. This module plays a crucial role in the concept of JPA as in this configuration file we will register the database and specify the entity class. Create a directory META-INF in the src/main/java folder and create the file persistence.xml inside it. Add the following code to it:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
	xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="JPAMappedbyExample" transaction-type="RESOURCE_LOCAL">
		<class>com.jcg.jpa.mappedBy.Employee</class>
		<class>com.jcg.jpa.mappedBy.Passport</class>

		<!-- Configuring The Database Connection Details -->
		<properties>
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpaMappedBy" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="" />
		</properties>
	</persistence-unit>
</persistence>

Notes:

  • In this example, we are connecting the application with the MySQL database. So, developers must add the MySQL-connector-java-<version>-bin.jar to the project
  • We have kept the javax.persistence.jdbc.password value as blank for simplicity, however, it is pure unto the user to keep it blank or set it during the MySQL configuration. If the user sets it, we need to provide the same password for this string

4. Run the Application

To run the application, Right click on the AppDemo class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 12: Run Application
Fig. 12: Run Application

5. Project Demo

Hereafter running the code, the application shows the following status as output:

Fig. 13: Application Output
Fig. 13: Application Output

That’s all for this post. Happy Learning!!

6. Conclusion

Through this example, we learned about the JPA implementation in Java. I hope this article served you whatever you were looking for. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of JPA mappedBy example.

Download
You can download the full source code of this example here: JPAMappedbyExample

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Naga
Naga
5 years ago

Hi,

So Other than the package where are you using the mapped by ?

-Naga

Back to top button