jpa

JPA CriteriaBuilder Example

The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, portable and easy to modify by changing the syntax i.e. the JPA queries are mainly used for building the dynamic queries whose exact structure is only known at the runtime. In this tutorial, we will show how to implement the JPA Criteria API with 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 Criteria API vs. JPQL

JPQL queries are defined as Strings, similar to the SQL. JPA Criteria Queries, on the other hand, is defined by the instantiation of the Java objects that represent the query elements. A major advantage of using the criteria API is that errors can be detected earlier, i.e. during the compilation time rather than at the runtime. For many developers, String-based JPQL queries, are easier to use and understand.

For simple static String-based queries, JPQL Queries (e.g. Named Queries) may be preferred. For dynamic queries i.e. building a query at runtime, the Criteria API is preferred as it eliminates the String concatenation needs. Both JPQL and JPA based queries are equivalent in power and efficiency, however, choosing one method over the other is a matter of personal preference.

1.2 How to use the JPA Criteria API

The criteria API can seem quite daunting at first but it’s not that bad once you are ok with its basic design approach. There are two main objects that developers will use to create the SQL query, namely the CriteriaBuilder object and a CriteriaQuery object. The first step is to handle a CriteriaBuilder object which serves as the main factory of the criteria queries and criteria query elements and then create a CriteriaQuery object. This is done with the following boiler-plate code, where emObj is an EntityManager object.

CriteriaBuilder cb = emObj.getCriteriaBuilder();
CriteriaQuery cqry = emObj.createQuery();

Do remember, CriteriaBuilder object can be obtained either by the EntityManagerFactory.getCriteriaBuilder() method or by the EntityManager.getCriteriaBuilder() method.

1.3 JPA Benefits

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

  • The benefit of using the JPA over any specific Object Relational Model (ORM) related libraries like Hibernate, iBatis etc. is that we don’t need to change the code when we change the vendor
  • The code is loosely coupled with the underlying ORM framework
  • Improves data security and data access to 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.4 Download & Install EclipseLink

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

1.5 Download and Install MySQL

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

Now, open up the Eclipse Ide and let’s see how to implement the JPA Criteria Builder API in Java using Eclipse Link and MySQL.

2. Java CriteriaBuilder Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, Eclipse Link 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: JPA CriteriaBuilder 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>JPACriteriaBuilder</groupId>
	<artifactId>JPACriteriaBuilder</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 jpaCriteriaBuilderDb with table: employee. Open the MySQL or the workbench terminal and execute the SQL script:

CREATE DATABASE jpaCriteriaBuilderDb;

USE jpaCriteriaBuilderDb;

CREATE TABLE employee (
  emp_id INTEGER NOT NULL,
  emp_name VARCHAR(120),
  emp_salary DOUBLE NOT NULL,
  emp_desig VARCHAR(200),
  PRIMARY KEY(emp_id)
);

INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (101, 'Java Code Geek', 40000.0, 'Chairman');
INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (102, 'Harry Potter', 35000.0, 'Chief Technical Officer');
INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (103, 'Lucifer Morningstar', 30000.0, 'Web Developer');
INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (104, 'April O'' Neil', 35000.0, 'Senior Technical Lead');
INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (105, 'Daniel Atlas', 32000.0, 'Chief Financial Officer');
INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (106, 'John Snow', 15000.0, 'Java Developer');
INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (107, 'Daenerys Targaryen', 35000.0, 'Business Analyst');
INSERT INTO employee (emp_id, emp_name, emp_salary, emp_desig) VALUES (108, 'Tyrion Lannister', 40000.0, 'Business Strategist');

SELECT * FROM employee;

DESC employee;

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 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>JPACriteriaBuilder</groupId>
	<artifactId>JPACriteriaBuilder</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>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.2.8.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.criteria.builder.

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

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.criteria.builder.

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

Repeat the step (i.e. Fig. 8) and enter the filename as: CriteriaBuilderDemo. The JPA entity-manager class will be created inside the package: com.jcg.jpa.criteria.builder.

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

3.3.1 Implementation of Model Class

This class simply maps a row in the employee table to a Java object. Add the following code to it:

Employee.java

package com.jcg.jpa.criteria.builder;

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

@Entity
@Table(name="employee")
public class Employee {

	@Id
	@GeneratedValue(strategy= GenerationType.AUTO) 	
	private int emp_id;
	private double emp_salary;
	private String emp_name, emp_desig;

	public Employee( ) {
		super();
	}

	public Employee(int eid, String ename, double esalary, String edesig) {
		super( );
		this.emp_id = eid;
		this.emp_name = ename;
		this.emp_salary = esalary;
		this.emp_desig = edesig;
	}

	public int getEmp_id() {
		return emp_id;
	}

	public void setEmp_id(int emp_id) {
		this.emp_id = emp_id;
	}

	public String getEmp_name() {
		return emp_name;
	}

	public void setEmp_name(String emp_name) {
		this.emp_name = emp_name;
	}

	public double getEmp_salary() {
		return emp_salary;
	}

	public void setEmp_salary(double emp_salary) {
		this.emp_salary = emp_salary;
	}

	public String getEmp_desig() {
		return emp_desig;
	}

	public void setEmp_desig(String emp_desig) {
		this.emp_desig = emp_desig;
	}

	public String toString() {
		return "Id?= " + emp_id + ", Name?= " + emp_name + ", Designation?= " + emp_desig + ", Salary?= " + emp_salary;
	}
}

3.3.2 Implementation of Utility Class

This is the service class which implements the Criteria Query part using the MetaData API initialization. Add the following code to it:

CriteriaBuilderDemo.java

package com.jcg.jpa.criteria.builder;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class CriteriaBuilderDemo {

	private static final String PERSISTENCE_UNIT_NAME = "JPACriteriaBuilder";	
	private static EntityManager entityMgrObj = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME).createEntityManager();	

	public static void main(String[] args) {

		CriteriaBuilder criteriaBuilderObj = entityMgrObj.getCriteriaBuilder();

		// Making The Query Object From The 'CriteriaBuilder' Instance
		CriteriaQuery<Object> queryObj = criteriaBuilderObj.createQuery();
		Root<Employee> from = queryObj.from(Employee.class);

		// Step #1 - Displaying All Records
		System.out.println("\n! Display All Records For The 'Employee' Table !\n");
		CriteriaQuery<Object> selectQuery = queryObj.select(from);
		TypedQuery<Object> typedQuery = entityMgrObj.createQuery(selectQuery);
		List<Object> employeeList = typedQuery.getResultList();

		if(employeeList != null && employeeList.size() > 0) {
			for(Object obj : employeeList) {
				Employee emp = (Employee)obj;
				System.out.println(emp.toString());
			}
		} else {
			System.out.println("! ALERT - No Employees Are Present In The 'Employee' Table !");
		}

		// Step #2 - Displaying All Records In An Ordered Fashion
		System.out.println("\n! Displaying All Records For The 'Employee' Table In An Asc. Order !\n");
		CriteriaQuery<Object> ascSelectQuery = queryObj.select(from);		
		ascSelectQuery.orderBy(criteriaBuilderObj.asc(from.get("emp_name")));
		TypedQuery<Object> ascTypedQuery = entityMgrObj.createQuery(ascSelectQuery);
		List<Object> ascEmployeeList = ascTypedQuery.getResultList();

		if(ascEmployeeList != null && ascEmployeeList.size() > 0) {
			for(Object obj : ascEmployeeList) {
				Employee emp = (Employee)obj;
				System.out.println(emp.toString());
			}
		} else {
			System.out.println("! ALERT - No Employees Are Present In The 'Employee' Table !");
		}
	}
}

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="JPACriteriaBuilder" transaction-type="RESOURCE_LOCAL">
		<class>com.jcg.jpa.criteria.builder.Employee</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/jpaCriteriaBuilderDb" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="" />
		</properties>
	</persistence-unit>
</persistence>

The persistence.xml file indicates that there is only one Persistence Unit mapped with the name JPACriteriaBuilder 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.

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 to this string

4. Run the Application

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

Fig. 11: Run Application
Fig. 11: Run Application

5. Project Demo

The code shows the following status as output:

Fig. 12: Application Output
Fig. 12: Application Output

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

6. Conclusion

Through this example, we learned about the JPA Criteria Builder 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 Criteria Builder.

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

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.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sergio M
6 years ago

Nice article, thanks !! I would like to suggest, in order to provide really compilation-time error checking that you use metamodel instead of Strings to refer object fields. You can have a look at https://tododev.wordpress.com/2014/08/05/compile-time-checking-jpa-queries/

Basically, you can replace from.get(“emp_name”) by the corresponding metamodel attribute. That way you will get compilation errors if the class attributes are changed.

Rodarigs
Rodarigs
5 years ago

when we we develop an appliction is the data is send by the user to the admin and he insert it through the backend?

Back to top button