Home Backend Development PHP Tutorial Java Backend Development: Dynamic Query Using JPA Criteria API

Java Backend Development: Dynamic Query Using JPA Criteria API

Jun 17, 2023 am 11:00 AM
java backend jpa criteria api Dynamic query

In Java back-end development, querying data is a very common operation, and using JPA (Java Persistence API) is a very popular method. JPA provides a flexible, reusable way to retrieve and manipulate data in a database. However, for dynamic queries (that is, the query needs to be adjusted according to different parameters), it may not be convenient to use traditional static query statements or JPQL (Java Persistence Query Language). In this case, using the JPA Criteria API can be more convenient and flexible.

JPA Criteria API is an object-oriented query method, which is implemented by assembling query conditions and returning results through code. Compared with traditional static query statements or JPQL, one of its main advantages is that it can dynamically splice different query conditions during the query process, and can better respond to changes in the data model. This article will introduce how to use the JPA Criteria API to perform dynamic queries.

  1. Entity Class

First, we need to have an entity class. Suppose we have a User entity class, which has fields such as id, name, age, gender, etc. Before using the JPA Criteria API, we need to define this entity class first.

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

    private Boolean gender;

    // 省略getter和setter方法
}
Copy after login
  1. CriteriaBuilder

Before using the JPA Criteria API, we need to obtain the CriteriaBuilder first. CriteriaBuilder is a factory class used to create various CriteriaQuery, Predicate and Expression. Usually, we can get CriteriaBuilder through EntityManager.

@PersistenceContext
private EntityManager entityManager;

public List<User> getUsers() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    // ... 继续后续操作
}
Copy after login
  1. CriteriaQuery

CriteriaQuery is used for query operations. We can use it to set the conditions of the query and the type of returned results. When setting query conditions, we can set multiple restrictions through Predicate. Predicate is a small tool in the Criteria API for building query conditions.

public List<User> getUsers(String name, Integer age, Boolean gender) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> root = cq.from(User.class);

    List<Predicate> predicates = new ArrayList<>();

    if (name != null) {
        Predicate namePredicate = cb.equal(root.get("name"), name);
        predicates.add(namePredicate);
    }

    if (age != null) {
        Predicate agePredicate = cb.greaterThanOrEqualTo(root.get("age"), age);
        predicates.add(agePredicate);
    }

    if (gender != null) {
        Predicate genderPredicate = cb.equal(root.get("gender"), gender);
        predicates.add(genderPredicate);
    }

    cq.where(predicates.toArray(new Predicate[0]));
    return entityManager.createQuery(cq).getResultList();
}
Copy after login

The above code demonstrates how to use CriteriaBuilder to create CriteriaQuery. First, we use EntityManager to get the CriteriaBuilder. Then, we create a query object CriteriaQuery cq, specifying that the result type of the query is User. Use Root root to construct query conditions, where root represents the User object. Next, we can use CriteriaBuilder to create Predicate objects and add them to the list. Finally, set the conditions into the CriteriaQuery and execute the query to return the results.

  1. Expression

Expression is another very useful concept in the Criteria API. It represents an operation expression that can be used to calculate and compare some complex data types. . When using Expression, we can perform more refined filtering under the original query conditions. For example, we can use the between method to query users whose age is within a certain range.

public List<User> getUsersInRange(Integer minAge, Integer maxAge) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> root = cq.from(User.class);

    Expression<Integer> ageExpression = root.get("age");

    Predicate agePredicate = cb.between(ageExpression, minAge, maxAge);
    cq.where(agePredicate);

    return entityManager.createQuery(cq).getResultList();
}
Copy after login

The above code queries users whose age is between minAge and maxAge. It should be noted that here we use Expression ageExpression, in order to let the JPA Criteria API understand that the age field we want to query is of integer type.

  1. Multiple table query

In some scenarios, we need to query multiple tables. At this point we need to use Join, which is the core concept used for multi-table queries. Suppose we have a Task entity class, which has two fields, id and userId. UserId is associated with the id field in the User entity class.

@Entity
@Table(name = "task")
public class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long userId;

    // 省略getter和setter方法
}
Copy after login

We can associate two entity classes through Join and query all Tasks under the specified User.

public List<Task> getUserTasks(Long userId) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Task> cq = cb.createQuery(Task.class);
    Root<Task> taskRoot = cq.from(Task.class);
    Join<Task, User> userJoin = taskRoot.join("user");

    Predicate predicate = cb.equal(userJoin.get("id"), userId);
    cq.where(predicate);

    return entityManager.createQuery(cq).getResultList();
}
Copy after login
  1. Paging query

Finally, we introduce how to implement paging query in JPA Criteria API. Compared with static queries, paging queries are also very common, and are especially important for scenarios with relatively large amounts of data. In the JPA Criteria API, we can use the setFirstResult and setMaxResults methods to specify the starting position of the query and the maximum number of returned results.

public List<User> getUsers(Integer pageNum, Integer pageSize) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> root = cq.from(User.class);

    int offset = (pageNum - 1) * pageSize;
    entityManager.createQuery(cq).setFirstResult(offset).setMaxResults(pageSize);

    return entityManager.createQuery(cq).getResultList();
}
Copy after login

The above code demonstrates how to set the paging query conditions. First, we calculate the offset through pageNum and pageSize, set the starting position, and then set the maximum number of returned results through setMaxResults. Of course, in practical applications, we can also perform paging queries in other ways.

Conclusion

JPA Criteria API is a very flexible and powerful tool that can provide good support in dynamic queries. Of course, in actual applications, we also need to consider issues such as performance, but it can make our code more readable, maintainable and scalable. I hope this article will be helpful to readers who are using JPA or considering using JPA.

The above is the detailed content of Java Backend Development: Dynamic Query Using JPA Criteria API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the five options for choosing the Java career path that best suits you? What are the five options for choosing the Java career path that best suits you? Jan 30, 2024 am 10:35 AM

There are five employment directions in the Java industry, which one is suitable for you? Java, as a programming language widely used in the field of software development, has always been popular. Due to its strong cross-platform nature and rich development framework, Java developers have a wide range of employment opportunities in various industries. In the Java industry, there are five main employment directions, including JavaWeb development, mobile application development, big data development, embedded development and cloud computing development. Each direction has its characteristics and advantages. The five directions will be discussed below.

Java Backend Development: Building Reactive APIs with Akka HTTP Java Backend Development: Building Reactive APIs with Akka HTTP Jun 17, 2023 am 11:09 AM

Reactive programming is becoming more and more important in today's web development. AkkaHTTP is a high-performance HTTP framework based on Akka, suitable for building reactive REST-style APIs. This article will introduce how to use AkkaHTTP to build a reactive API, while providing some practical examples. Let’s get started! Why choose AkkaHTTP When developing reactive APIs, it is important to choose the right framework. AkkaHTTP is a very good choice because

How to solve database transaction problems in Java back-end function development? How to solve database transaction problems in Java back-end function development? Aug 04, 2023 pm 07:45 PM

How to solve database transaction problems in Java back-end function development? In the development of Java back-end functions, functions involving database operations are very common. In database operations, transactions are a very important concept. A transaction is a logical unit consisting of a sequence of database operations that is either fully executed or not executed at all. In practical applications, we often need to ensure that a set of related database operations are either all successfully executed or all rolled back to maintain data consistency and reliability. So, how to develop in Java backend

How to handle cross-domain requests in Java backend function development? How to handle cross-domain requests in Java backend function development? Aug 05, 2023 am 09:40 AM

How to handle cross-domain requests in Java backend function development? In a development model where front-end and back-end are separated, it is a very common scenario for the front-end to send requests to the back-end API interface to obtain data through JavaScript. However, due to the browser's same-origin policy, there are restrictions on cross-domain requests. Cross-domain request means that the front-end page requests servers with different domain names, different ports or different protocols through AJAX and other methods. This article will introduce a common method for handling cross-domain requests in the development of Java back-end functions, with code examples. Solve cross-domain

Java Backend Development: Building Secure RESTful APIs Java Backend Development: Building Secure RESTful APIs Jun 17, 2023 am 08:31 AM

With the continuous development of Internet technology, developing and designing RESTful API has become a vital task. RESTful API provides a simple, lightweight, flexible and reliable mechanism for interaction between different services. At the same time, building secure RESTful APIs is becoming increasingly important. In this article, we will explore how to build a secure RESTful API in Java backend development. 1. Understanding RESTfulAPI RESTfulAPI is a

How to implement data persistence in Java back-end function development? How to implement data persistence in Java back-end function development? Aug 07, 2023 am 10:21 AM

How to implement data persistence in Java back-end function development? With the rapid development of the Internet, data has become a core asset that cannot be ignored by organizations and enterprises. In Java back-end development, achieving data persistence is an important task. This article will introduce several common data persistence methods and use code examples to show how to implement data persistence in Java. 1. Relational database Relational database is one of the most common data persistence methods. In Java we can use JDBC (JavaDa

How to implement search function in Java backend function development? How to implement search function in Java backend function development? Aug 05, 2023 am 11:09 AM

How to implement search function in Java backend function development? Search functionality is an essential feature in modern applications. Whether searching for products on e-commerce platforms or searching for friends on social media, the search function provides users with a convenient and efficient way to obtain information. In Java backend development, we can use various technologies and libraries to implement search functions. This article will introduce a commonly used method to implement the search function, and give code examples using the Java language as an example. In Java backend development, we usually

How to deal with exceptions in Java backend function development? How to deal with exceptions in Java backend function development? Aug 06, 2023 pm 04:06 PM

How to deal with exceptions in Java backend function development? In Java backend development, handling exception situations is a very important task. Exceptions may occur at runtime, such as null pointer exceptions, array out-of-bounds exceptions, etc., or they may be exceptions in business logic, such as resource not found, insufficient permissions, etc. Properly handling these exceptions can not only improve the stability and reliability of the code, but also improve the maintainability and readability of the code. This article will introduce how to reasonably handle abnormal situations in Java back-end development and give corresponding codes.

See all articles