JPA - Introduction to Query Methods
Last Updated :
08 Apr, 2024
In Java, JPA can defined as Java Persistence API. It can provide a powerful and intuitive way to interact with the database using object-oriented paradigms. Query Methods Can offer a convenient approach to define database queries directly within the repository and it can reduce the boilerplate code and enhance the code readability of the JPA Application.
Understanding of the JPA Query Methods
JPA Query Methods can provide a straightforward way to define database queries directly within the repository interfaces. These methods follow the naming convention based on the method signatures and keywords like findBy, readBy, queryBy, etc. which are automatically translated into the SQL queries by the JPA provider.
Steps to Implement JPA Query Methods
1. Define the Entity Class
We can create the Entity class that can represent with @Entity to mark it as the JPA entity and It can define the attributes to the map to database columns and it can include the appropriate annotations such as @Id, @GenerateValue, and others as needed.
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and Setters
}
2. Create the EntityManager
We can obtain of the EntityManager from the EntityManagerFactory. EntityManager is the responisible for the managing the entity instances and it can persisting the entities to the database and executing the queries.
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-example");
EntityManager em = emf.createEntityManager();
3. Declare the Query Methods
We can define in the application code to execute the database queries using JPQL(Java Persistence Query Language). It is the platform independent query language similar to the SQL but operates on the entities rather than the database tables.
4. Execute the Query Methods
We can invoke the defined methods to the interact with the database. It can pass the EntityManager instance along with the other parameters to the query methods for the execution.
List<Product> laptopProducts = findProductsByName(em, "Laptop");
System.out.println("Products with name 'Laptop': " + laptopProducts);
List<Product> affordableProducts = findProductsByPriceLessThan(em, 700.00);
System.out.println("Affordable products (price less than $700): " + affordableProducts);
long laptopCount = countProductsByName(em, "Laptop");
System.out.println("Count of products with name 'Laptop': " + laptopCount);
Example Project
Step 1: Create the new JPA project using the InteljIdea named as jpa-query-method-demo.
Step 2: Open the pom.xml and add the below dependencies into the project.
Dependencies:
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
Once create the project then the file structure looks like the below image.
file structure
Step 3: Open the persistence.xml and put the below code into the project and it can configure the database of the project.
XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence
https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
version="3.0">
<persistence-unit name="default">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/example"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Step 4: Create the new Entity Java class named as the Product.
Go to src > main > java > Product and put the below code.
Java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
Step 5: create the new Java class named as the MainApp.
Go to src > main > java > MainApp and put the below code.
Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.util.List;
public class MainApp {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();
// Retrieve products using Query Methods
List<Product> laptopProducts = findProductsByName(em, "Laptop");
System.out.println("Products with name 'Laptop': " + laptopProducts);
List<Product> affordableProducts = findProductsByPriceLessThan(em, 700.00);
System.out.println("Affordable products (price less than $700): " + affordableProducts);
long laptopCount = countProductsByName(em, "Laptop");
System.out.println("Count of products with name 'Laptop': " + laptopCount);
em.close();
emf.close();
}
// Query Methods Implementation
public static List<Product> findProductsByName(EntityManager em, String name) {
return em.createQuery("SELECT p FROM Product p WHERE p.name = :name", Product.class)
.setParameter("name", name)
.getResultList();
}
public static List<Product> findProductsByPriceLessThan(EntityManager em, double price) {
return em.createQuery("SELECT p FROM Product p WHERE p.price < :price", Product.class)
.setParameter("price", price)
.getResultList();
}
public static long countProductsByName(EntityManager em, String name) {
return em.createQuery("SELECT COUNT(p) FROM Product p WHERE p.name = :name", Long.class)
.setParameter("name", name)
.getSingleResult();
}
}
pom.xml
XML
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>jpa-query-method-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>jpa-query-method-demo</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<junit.version>5.9.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>
<build>
<plugins>
</plugins>
</build>
</project>
Step 6: Once the project is completed, run the application then show the laptop name and its prices less that 700 as the count as output. Refer the below image for the better understanding of the concept.

In the above project, it can demonstrates the how to use the JPA Query methods in the non-Spring environment where the EntityManager is manually managed for the database interaction.
Conclusion
JPA Query Methods offers the convenient and efficient way to the interact with the database by defining the queries declaratively within the query methods. By the following the simple naming convention and leveraging the derived query method rules and developers can easily construct the database queries withou the writing the explicit SQL statements. Understanding the various keywords, expressions and customization options associated with the Query Methods that can empowers the developers to build the robust and maintainable the database driven applications in the Java.
Similar Reads
JPA - Query Creation from Method Names
In Java, JPA can defined as Java Persistence API can provide a powerful way to interact with databases in Java applications. One of the key features of the JPA is the Query Creation from the Method names and it allows the developers to dynamically create the database queries based on the method name
5 min read
JPA - Introduction
JPA can be defined as Java Persistence API. It is the Java specification that can provide a standardized way to manage the relational data in Java applications. JPA facilitates the management of the database operations and mapping of the Java objects to database tables by defining the concepts and A
4 min read
Derived Query Methods in Spring Data JPA Repositories
Spring Data JPA helps manage database operations in Java applications with ease. One powerful feature is derived query methods, which let you perform common database queries by just naming the method. This way, you donât have to write complex SQL or JPQL queries manually. Instead, you can use simple
6 min read
JPA - Entity Introduction
Java Persistence API (JPA) can facilitate the development of Java applications by providing a framework for managing relational data in Java applications and JPA is one of the key concepts in entities. Entities can represent and use persistent data stored in a relational database map to correspondin
7 min read
findBy Methods in Spring Data JPA Repositories
Spring Data JPA abstracts the boilerplate code required to interact with the database, allowing developers to focus more on business logic rather than database connectivity and query formation. The findBy() method, in particular, is a part of the repository layer in Spring Data JPA, enabling develop
5 min read
How to Filter Query Results in MySQL
MySQL, popular among relational database management systems for its performance, reliability, and ease of use, is a database that does its task very well. Regardless of whether you are an experienced web developer or just at the beginning of your data journey, knowing how to speed up filters in quer
5 min read
Dynamic Query in Java Spring Boot with MongoDB
Most of todayâs applications require great flexibility regarding database querying. MongoDB provides an effective option for solving complex queries using this kind of storage for documents. Integrating it with Spring Boot makes things even smoother. In this article, we will look at how to create dy
4 min read
Spring Data JPA @Query Annotation with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. @Query Annotation is used for defining custom queries
7 min read
MongoDB Query and Projection Operator
MongoDB query operators play a crucial role in interacting with data stored in MongoDB collections. Similar to SQL, these operators enable users to filter, compare, and manipulate data efficiently. Query operators allow for value-based comparisons, logical evaluations, and array operations, making d
11 min read
Introduction to Spring Data Elasticsearch
Spring Data Elasticsearch is part of the Spring Data project that simplifies integrating Elasticsearch (a powerful search and analytics engine) into Spring-based applications. Elasticsearch is widely used to build scalable search solutions, log analysis platforms, and real-time data analytics, espec
4 min read