Open In App

JPA – Introduction to Query Methods

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads