Query Optimization Using QueryDSL in a Spring Boot Application – DS
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 query using QueryDSL in spring boot application, We have to follow below points.
1) 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 Primary key and two other column:
@Data @Builder @AllArgsConstructor @NoArgsConstructor @Entity public class Testing { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; }
3) Create an 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 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;
Related Blog
- Integrate the Sonarqube with Spring Boot
- How to Create Crud Application in Spring Boot?
- Integrate the Eureka In Spring Boot Project for Microservices