Query Optimization Using QueryDSL in a Spring Boot Application
What Is QueryDSL?
QueryDSL (Query Domain Specific Language) is a Java-based framework. It is a type-safe, fluent API for building SQL-like queries in a programmatic way.
Official Documentation for the latest version of QueryDSL
Key Features and Concepts of QueryDSL
- Type Safety:
- Code Generation
- JPA Integration
- Support for Collections
- DSL for Expressing Predicates
- Support for Joins
- Extensibility
Process of Query Optimization Using QueryDSL
To optimize the query using QueryDSL in the spring boot application, We have to follow the below points.
- Add dependency for QueryDSL in your application:
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>5.0.0</version>
</dependency>
2) Create An entity Class Testing with a Primary key and two other columns:
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Testing {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
}
3) Create a Repository class for custom functions:
import org.springframework.beans.factory.annotation.Autowired;
import com.querydsl.jpa.impl.JPAQueryFactory;
public class TestingRepository {
@Autowired
private EntityManager entityManager;
public List<Testing> findPeopleByLastName(String lastName) {
JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);
QTesting person = QTesting.testing;
return queryFactory.selectFrom(person)
.where(person.lastName.eq(lastName))
.fetch();
}
}
4) Create a Database table
CREATE TABLE `testing` (
`id` bigint NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Originally published at https://www.devstringx.com on Nov 11, 2023