Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
JPA - Introduction to Query Methods
Next article icon

JPA - Introduction to Query Methods

Last Updated : 08 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Query File
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.

querymethodlog-compressed

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.


Next Article
JPA - Introduction to Query Methods

S

syam1270
Improve
Article Tags :
  • Advance Java
  • JPA

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
    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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences