Step-by-Step Implementation of JPA Query Creation from Method Names

We can develop a simple JPA application that can demonstrate the Query Creation from the Method Names of the application.

Step 1: Create the new JPA project using the IntelliJ Idea named query-creation-demo. After creating the project, the file structure looks like the below image.


Step 2: Open the open.xml and add the below dependencies into the project.

<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>


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="examplePU">
        <class>User</class>
        <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 User.

Go to src > main > java > User 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 User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String email;

    // Constructors, getters, and setters
    public User() {}

    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}


Step 5: Create the new Entity Java class named as MainApplication.

Go to src > main > java > MainApplication and put the below code.

Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;

import java.util.List;

public class MainApplication {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU");
        EntityManager em = emf.createEntityManager();

        // Create and persist some users
        em.getTransaction().begin();
        User user1 = new User("Raju", "rajukumar@example.com");
        User user2 = new User("Eswar", "eswar@example.com");
        em.persist(user1);
        em.persist(user2);
        em.getTransaction().commit();

        // Query users by username
        em.getTransaction().begin();
        TypedQuery<User> queryByUsername = em.createQuery("SELECT u FROM User u WHERE u.username = :username", User.class)
                .setParameter("username", "JohnDoe");
        List<User> usersByUsername = queryByUsername.getResultList();
        if (!usersByUsername.isEmpty()) {
            for (User user : usersByUsername) {
                System.out.println("User found by username: " + user);
            }
        } else {
            System.out.println("No user found with the specified username.");
        }

        // Query users by email domain
        TypedQuery<User> queryByEmail = em.createQuery("SELECT u FROM User u WHERE u.email LIKE :domain", User.class)
                .setParameter("domain", "%example.com");
        List<User> usersByEmail = queryByEmail.getResultList();
        if (!usersByEmail.isEmpty()) {
            for (User user : usersByEmail) {
                System.out.println("User found by email domain: " + user);
            }
        } else {
            System.out.println("No user found with the specified email domain.");
        }
        em.getTransaction().commit();

        em.close();
        emf.close();
    }
}

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>query-creation-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>query-creation-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. It will then show the usernames and email based on the query as output. Refer the below output image for the better understanding of the concept.

By the following the above steps of the article, developers can gain the solid understanding of the how to effectively Query Creation from Method Names in their JPA applications.



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 names.

Similar Reads

Creating Queries from Method Names in JPA

Query Creation from the Method Names is a feature provided by the frameworks like the Spring Data JPA but it can also be implemented directly with the JPA. It can involve defining the repository methods in such a way that the framework automatically generates the corresponding JPQL queries on method names....

Step-by-Step Implementation of JPA Query Creation from Method Names

We can develop a simple JPA application that can demonstrate the Query Creation from the Method Names of the application....