Spring - QueryDSL
Overview
Spring Boot QueryDSL lets you query the database using domain specific language similar to SQL.
Github: https://github.com/gitorko/project75
Spring QueryDSL
Let's say you used Spring Data to query the db by using spring naming convention. If your table has 100's of column and you have to query by any column you can't write 100 access functions. This is where query dsl comes into play.
Code
1package com.demo.project75;
2
3import java.util.stream.IntStream;
4
5import com.demo.project75.domain.Customer;
6import com.demo.project75.repository.CustomerRepository;
7import org.springframework.boot.CommandLineRunner;
8import org.springframework.boot.SpringApplication;
9import org.springframework.boot.autoconfigure.SpringBootApplication;
10
11@SpringBootApplication
12public class Main {
13
14 public static void main(String[] args) {
15 SpringApplication.run(Main.class, args);
16 }
17
18 public CommandLineRunner onStart(CustomerRepository customerRepository) {
19 return (args) -> {
20 //Insert test data
21 IntStream.range(0, 5).forEach(i -> {
22 customerRepository.save(Customer.builder()
23 .firstName("firstname_" + i)
24 .lastName("lastname " + i)
25 .age(30)
26 .email("email@email.com")
27 .build());
28 });
29 };
30 }
31}
32
33
34
35
It uses in memory h2 db to persist.
Setup
1# Project 75
2
3Spring Boot - Querydsl
4
5[https://gitorko.github.io/spring-boot-querydsl/](https://gitorko.github.io/spring-boot-querydsl/)
6
7### Version
8
9Check version
10
11```bash
12$java --version
13openjdk version "21.0.3" 2024-04-16 LTS
14```
15
16### Dev
17
18To run the code.
19
20```bash
21./gradlew clean build
22./gradlew bootRun
23```
Testing
You can now search based on all the columns of the db and get the response.
http://localhost:8080/users?age=30
http://localhost:8080/users?firstName=firstname_0
http://localhost:8080/users?firstName=firstname_0&age=30
References
Spring Query DSL : http://www.querydsl.com/static/querydsl/latest/reference/html/ch02.html
comments powered by Disqus