Skip to content

beanbroker/querydsl_java_spring

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

7 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

https://beanbroker.github.io/2019/07/13/Java/java_querydsl_gradle4-1/

1. ๊ธฐ๋ณธ์…‹ํŒ…

5๋ฒ„์ ผ๊ณผ 4๋ฒ„์ ผ์˜ ์ฐจ์ด๋ฅผ ์ถ”ํ›„ ๋ธ”๋กœ๊ทธ์— ๊ณต์œ ํ• ์˜ˆ์ •!

ํšŒ์‚ฌ์—์„œ gradle 4๋ฒ„์ ผ์„ ์‚ฌ์šฉํ•จ์„ ์ธ์ง€!

build.gradle์—์„œ ๊ฐ€์žฅ ์ค‘์š”ํ•˜๊ฒŒ ๋ด์•ผํ•˜๋Š” ๋ถ€๋ถ„์€ // querydsl ์ ์šฉ ์ด๋ผ ์ ํ˜€์žˆ๋Š” ๋ถ€๋ถ„

build.gradle (๋ฉ”์ด๋ธ์ผ ๊ฒฝ์šฐ ๋‹ค๋ฅธ๋ฐ๊ณณ์—์„œ ์ฐพ์•„์„œ....ํ•˜์‹œ๊ธธ..)

build.gradle

buildscript {
    ext {

        springBootVersion = '2.1.6.RELEASE'
        querydslPluginVersion = '1.0.10'
    }
    repositories {
        mavenCentral()
        maven { url "https://plugins.gradle.org/m2/" } // plugin ์ €์žฅ์†Œ
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("gradle.plugin.com.ewerk.gradle.plugins:querydsl-plugin:${querydslPluginVersion}")

    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.beanbroker'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compile("com.querydsl:querydsl-jpa") // querydsl
    compile("com.querydsl:querydsl-apt") // querydsl

    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')

//    runtimeOnly('com.h2database:h2')
    runtimeOnly 'mysql:mysql-connector-java'
    compile('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

// querydsl ์ ์šฉ
apply plugin: "com.ewerk.gradle.plugins.querydsl"
def querydslSrcDir = 'src/main/generated'

querydsl {
    library = "com.querydsl:querydsl-apt"
    jpa = true
    querydslSourcesDir = querydslSrcDir
}

sourceSets {
    main {
        java {
            srcDirs = ['src/main/java', querydslSrcDir]
        }
    }
}

}


def querydslSrcDir = 'src/main/generated'

querydsl {
    library = "com.querydsl:querydsl-apt"
    jpa = true
    querydslSourcesDir = querydslSrcDir
}

compileQuerydsl{
    options.annotationProcessorPath = configurations.querydsl
}

configurations {
    querydsl.extendsFrom compileClasspath
}

sourceSets {
    main {
        java {
            srcDirs = ['src/main/java', querydslSrcDir]
        }
    }
}

application.yml

spring: 
    datasource:
        url: jdbc:mysql://localhost:3306/study
        username: root
        password: password


user.sql

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `age` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_id` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

UserEntity.class

@Data
@Entity(name = "users")
public class UserEntity {

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

    private String userId;
    private String name;
    private int age;

    @Builder
    public UserEntity(String userId, String name, int age){

        this.userId = userId;
        this.name = name;
        this.age = age;

    }

}

2. repository

๋ฐ˜๋“œ์‹œ ์ฝ๊ณ  ์™œ ๋ ˆํฌ๊ตฌ์„ฑ์ด ์•„๋ž˜์™€ ๊ฐ™์ด ์ง„ํ–‰๋˜๋Š”์ง€!

์•„๋ž˜์˜ ์„ค๋ช…์„ ์ฝ์–ด์•ผํ•˜๋Š”์ด์œ ! ( you must )

you must first define a fragment interface and an implementation for the custom functionality, as shown in the following example:

https://docs.spring.io/spring-data/jpa/docs/2.1.3.RELEASE/reference/html/#repositories.custom-implementations

์ฐธ๊ณ ํ•˜๋ฉด ์ข‹์„ ์‚ฌํ•ญ https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl

UserRepository.java

import com.beanbroker.sample.api.user.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends
        JpaRepository<UserEntity, Long>,
//        QuerydslPredicateExecutor<UserEntity>,
        UserRepositoryCustom {

}

UserRepositoryCustom.java

import com.beanbroker.sample.api.user.entity.UserEntity;

public interface UserRepositoryCustom {


    UserEntity getByUserId(String userId);
}

UserRepositoryImpl.java

import com.beanbroker.sample.api.user.entity.QUserEntity;
import com.beanbroker.sample.api.user.entity.UserEntity;
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;

public class UserRepositoryImpl extends QuerydslRepositorySupport
        implements UserRepositoryCustom {

    private static final QUserEntity table = QUserEntity.userEntity;


    /**
     * Creates a new {@link QuerydslRepositorySupport} instance for the given domain type.
     *
     * @param domainClass must not be {@literal null}.
     */
    public UserRepositoryImpl() {
        super(UserEntity.class);
    }

    @Override
    public UserEntity getByUserId(String userId) {

        return  from(table)
                .where(table.userId.eq(userId))
                .fetchOne();

    }
}

3. Service and Domain and Controller

์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฐ‘ ์ค‘๋ณต์ฒ˜๋ฆฌ ์•ˆ๋˜์–ด์žˆ์Œ ๊ทธ๋ƒฅ ์“ฐ๋Š” ๋ฐฉ๋ฒ•๋งŒ ์•Œ๊ณ  ์•Œ์•„์„œ

UserService.java

import com.beanbroker.sample.api.user.domain.UserInfo;
import com.beanbroker.sample.api.user.entity.UserEntity;
import com.beanbroker.sample.api.user.repository.UserRepository;
import javassist.NotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    public void createUser(){


        userRepository.save(
                new UserEntity("beanbroker", "pkj", 32)
        );

    }

    public UserEntity getUserId(String userId) throws NotFoundException {


        Optional<UserEntity> userEntity = Optional.ofNullable(userRepository.getByUserId(userId));

        if(!userEntity.isPresent()){
            throw new NotFoundException("Not Found");
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserAge(userEntity.get().getAge());
        userInfo.setUserName(userEntity.get().getName());

        return userEntity.get();

    }
}

UserInfo.java

entity์™€ client์—๊ฒŒ ๊ฐˆ response๊ฐ€ ์™œ๋”ฐ๋กœ๋”ฐ๋กœ ๋‚˜๊ฐ€์•ผํ• ๊ฐ€๋ผ๋Š” ๊ณ ๋ฏผ์„ ๊ผญํ•˜์ž...

public class UserInfo {

    private String userName;
    private int userAge;


    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
}

UserController.java

@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping("/user")
    public UserEntity testUser() throws NotFoundException {



        userService.createUser();

        return userService.getUserId("beanbroker");
    }
}

์•ฝ์†์ด ์žˆ์œผ๋ฏ€๋กœ ๋น ๋ฅด๊ฒŒ ํŠ€ํŠ€ ๋‹ค์Œ์žฅ์—์„œ github๊ณผ ๋‹ค๋ฅธ ๋ถ€๋ถ„๋“ค ๋”์ž์„ธํ•˜๊ฒŒ

2019๋…„ 7์›” 17์ผ ๊นƒํ—™ ์ถ”๊ฐ€

git source ๋งํฌ


PREDICATOR

git source ๋งํฌ

kotlin_version ๋งํฌ

PREDICATOR๊ฐ€ ์™œํ•„์š”ํ• ์ง€๋Š” ๋™์ ์ฟผ๋ฆฌ๋ฅผ ๋งค๋ฒˆ๋งค๋ฒˆ function์œผ๋กœ ์ถ”๊ฐ€ํ•˜์—ฌ ์“ธ๋ฐ์—†๋Š” ๋ฉ”์†Œ๋“œ ์ถ”๊ฐ€๋ฅผ ๋ฐฉ์ง€

๋ฐ”๋กœ ์†Œ์Šค ์นด์ฆˆ์•„

์ค‘์š”๋ถ€๋ถ„ ๋งค์šฐ ์ค‘์š”

๊ดœํžˆ ์ดํŽ™ํ‹ฐ๋ธŒ์ž๋ฐ”์—์„œ ๋นŒ๋”๋ฅผ ์จ๋ผ๋ผ๊ณ  ํ•˜๋Š”๊ฒƒ์ด ์•„๋‹˜!

UserPredicator.java

package com.beanbroker.sample.api.user.service;

import com.beanbroker.sample.api.user.entity.QUserEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import org.springframework.util.StringUtils;

public class UserPredicator {

    private static final QUserEntity table = QUserEntity.userEntity;

    private BooleanBuilder builder = new BooleanBuilder();


    public UserPredicator userId(String userId){

        if(userId != null){
            builder.and(table.userId.eq(userId));
        }
        return this;
    }

    public UserPredicator name(String name){

        if(name != null){
            builder.and(table.name.eq(name));
        }
        return this;
    }

    public UserPredicator age(int age){

        if(age > 0){
            builder.and(table.age.eq(age));
        }
        return this;
    }

    public Predicate values(){

        return builder.getValue();
    }
}

์ฐธ์‰ฌ์ฃ ์ž‰?

UserRepositoryCustom.java

import com.beanbroker.sample.api.user.entity.UserEntity;
import com.querydsl.core.types.Predicate;
public interface UserRepositoryCustom {


    UserEntity getByUserId(String userId);
    UserEntity getUserInfoWithPredicator(Predicate predicate);
}

UserRepositoryImpl.java

public class UserRepositoryImpl extends QuerydslRepositorySupport
        implements UserRepositoryCustom {

    private static final QUserEntity table = QUserEntity.userEntity;


    /**
     * Creates a new {@link QuerydslRepositorySupport} instance for the given domain type.
     *
     * @param domainClass must not be {@literal null}.
     */
    public UserRepositoryImpl() {
        super(UserEntity.class);
    }

    @Override
    public UserEntity getByUserId(String userId) {

        return  from(table)
                .where(table.userId.eq(userId))
                .fetchOne();

    }

    @Override
    public UserEntity getUserInfoWithPredicator(Predicate userPredicator) {
        return from(table)
                .where(userPredicator)
                .fetchOne();
    }
}

์…‹ํŒ…์€ ๋๋‚ซ๋Š”๋ฐ how to use?

์•„๋ž˜๊ฐ€ ํ•ต์‹ฌ์ฝ”๋“œ

 public UserEntity getUserInfoWithPredicator(
            String userId,
            String name,
            int age

    ){



        return userRepository.getUserInfoWithPredicator(
                setUserQuery(userId, name, age)
        );
    }


    private Predicate setUserQuery( String userId,
                                    String name,
                                    int age){

        return new UserPredicator()
                .userId(userId)
                .name(name)
                .age(age)
                .values();

    }

๊ทธ๋Ÿผ ์จ๋ณด์ž

   UserEntity test1 = userService.getUserInfoWithPredicator(
                "beanbroker",
                null,
                0

        );

        System.out.println(test1.toString());


        UserEntity test2 = userService.getUserInfoWithPredicator(
                "beanbroker",
                    "pkj",
                0

        );


        System.out.println(test2.toString());

        UserEntity test3 = userService.getUserInfoWithPredicator(
                null,
                null,
                32

        );

        System.out.println(test3.toString());

์•„ ์š”์ฆ˜์€ ์™œ ์ €๋ ‡๊ฒŒ์จ์•ผํ•˜๋Š”์ง€ ์„ค๋ช… ์ ๋Š”๊ฒŒ ๊ท€์ฐฎ๋‹ค.... ํ™œ์šฉ๋ฐฉ๋ฒ•์€ ๋‹ค์–‘ํ•˜๋‹ˆ! ์ž˜์‚ฌ์šฉํ•ฉ์‹œ๋‹น

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages