728x90

실무에서 JPA를 활용하다보면 Entity 생성시 
@NoargsConstructor (access = AccessLevel.PROTECTED) 이라는 Annotation을 붙여서 개발을 하게 된다. 이에 조금 더 정확히 이해하고자 이번 블로그 글로 언급하고자 한다.

이 글을 읽는 분들은 모두 알다시피 Lombok 라이브러리에는 생성자 관련한 두개의 어노테이션이 존재한다.

  • AllargsConstructor
  • NoArgsConstructor

 

1. AllargsConstrutor


말 그대로 '모든 매개변수 생성자'인 것 처럼 해당 클래스 내의 모든 변수값을 가진 생성자를 자동으로 만들어 준다.

@Setter
@Getter
@AllArgsConstructor
public class testDto {

    private String id;
    private String userName;
    private String Age;
    private String address;


}


// 서로 같다.

@Setter
@Getter
public class testDto {

    private String id;
    private String userName;
    private String Age;
    private String address;

    public testDto(String id, String userName, String age, String address) {
        this.id = id;
        this.userName = userName;
        this.Age = age;
        this.address = address;
    }
}

앗 생성자가 이미 생성되었다.

 

2. NoArgsConstructor


해당 어노테이션의 의미는 말 그대로 "아무런 매개변수가 없는 생성자" 이다.

@Setter
@Getter
@NoArgsConstructor
public class testDto {

    private String id;
    private String userName;
    private String age;
    private String address;
    
}

// 같다.

@Setter
@Getter
public class testDto {

    private String id;
    private String userName;
    private String age;
    private String address;


    public testDto() {
    }
}

앗 이미 생성되었다..


특히 생성자 접근 Level을 다음과 같은 설정값으로 줄 수 있다.

access = AccessLevel.PROTECTED 
access = AccessLevel.PRIVATE

자바 개발자라면 모두 아는 public / protected / private 접근 제한으로 

접근 Level 접근 할 수 없는 클래스
protected 다른 패키지에 소속된 클래스 (상속 제외)
private 모든 외부 클래스

 


간단히 @AllargsConstructor @NoArgsConstructor에 대해서 알아봤고 이제 이 포스트의 진짜 주제에 대해 알아보자.

Entity Class에는

@NoArgsConstructor(access = AccessLevel.PROTECTED)을 사용할까?
@NoArgsConstructor(access = AccessLevel.PRIVATE)는 안되는 건가?

 


주저리 주저리 설명하기 보다 코드로 살펴보자.

1. @NoArgsConstructor(access = AccessLevel.PROTECTED)

PROTECTED

 

2. @NoArgsConstructor(access = AccessLevel.PRIVATE)

PRIVATE 

 

AccessLevel을 PRIVATE로 설정했을 경우에는 다음과 같은 에러가 발생한다.

Class 'StoreEntity' should have [public, protected] no-arg constructor 

 

JSR-000338의 Entity 설명을 보면

The entity class must have a no-arg constructor. The entity class may have other constructors as well.
The no-arg constructor must be public or protected.
// Entity 클래스는 매개변수가 없는 생성자의 접근 레벨이 public 또는 protected로 해야 한다.

... 

An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself.
// 인스턴스 변수는 직접 접근이 아닌 내부 메소드로 접근해야 한다.

이에 따라 @Entity 선언 후 @NoArgsContructor에서 접근 Level에 따라 경고가 발생하고 있는 것이다. (Complie시 오류 검출 안됌)
또한 Entity 클래스 인스턴스 변수는 직접 접근이 아닌 내부 메소드로 접근해야 한다. (ex. Getter, Setter 사용)


결과부터 이야기하자면 그 원인은

Entity Proxy 조회

때문이다.

Proxy에 대한 설명은 해당 링크 참고 https://erjuer.tistory.com/105

 

[JPA] 프록시(Proxy)와 엔티티 연관 관계(LAZY, EAGER)

실무에서 조회기능을 메인으로 개발하고 있다보니 JPA 데이터 조회 최적화에 항상 관심을 가지고 있다. 특히 엔티티 설계시 엔티티간의 연관관계에 대해 중점적으로 설계하였고 이를 실무 개발

erjuer.tistory.com

 


예시를 들었던 음식 엔티티 클래스 FoodEntity(이하 Food), 음식점 클래스 StoreEntity (이하 Store)로 살펴보자.
Food와 Store는 N : 1 관계이다. 

총 4개의 경우의 수를 살펴보자.

  1. Food와 Store 모두 (access = AccessLevel.PROTECTED)
  2. Food : (access = AccessLevel.PROTECTED) , Store  : (access = AccessLevel.PRIVATE)
  3. Food : (access = AccessLevel.PRIVATE) , Store  : (access = AccessLevel.PROTECTED)
  4. Food와 Store 모두 (access = AccessLevel.PRIVATE)


이며 조회를 위한 전제 조건은 Proxy를 활용할 것이므로

  • @ManyToOne(fetch = FetchType.LAZY)

이다.

조회 Test는 다음과 같은 로직으로 되어 있다.

@SpringBootTest
public class ProxyTest {


    @Autowired
    private EntityManager em;



    @Test
    @Transactional
    public void proxyTest(){

        FoodEntity foodEntity = em.find(FoodEntity.class,5L); // food_id 값이 5L인 데이터를 찾는다.
        System.out.println("======= 쿼리 전송 =======");

        System.out.println("Food ID : " +foodEntity.getFoodId());
        System.out.println("Food Name : " + foodEntity.getFoodName());
        System.out.println("Food Calorie : " + foodEntity.getFoodCalorie());
        System.out.println(foodEntity.getStoreEntity().getClass());


        System.out.println("======= 쿼리 결과 =======");

        System.out.println("///////////////////////////////");
        System.out.println("///////////////////////////////");

        System.out.println("======= Store 데이터 =======");
        System.out.println("Store ID : " + foodEntity.getStoreEntity().getStoreId());
        System.out.println("Store Name : " + foodEntity.getStoreEntity().getStoreName());
        System.out.println("Store Address : " + foodEntity.getStoreEntity().getAddress());
        System.out.println("Store Number : " + foodEntity.getStoreEntity().getStoreNumber());

        em.close();
    }

 

1.  Food와 Store 모두 (access = AccessLevel.PROTECTED) : 정상 동작

이상 없이 조회된다.

정상 조회

======= 쿼리 전송 =======
Food Proxy ? Entity : class com.jpastudy.ms.domain.Entity.FoodEntity // 실제 Entity
Food ID : 5
Food Name : 항정살
Food Calorie : 500
Store Proxy ? Entity : class com.jpastudy.ms.domain.Entity.StoreEntity$HibernateProxy$LDEXNcvd
// Proxy
======= 쿼리 결과 =======

콘솔에서 FoodEntity 조회시에는 실제 Entity가 조회 되지만 StoreEntity 조회시 HibernateProxy 클래스를 사용하는 것을 확인 할 수 있다.

 

2. Food : (access = AccessLevel.PROTECTED) , Store  : (access = AccessLevel.PRIVATE) : 오류 발생

앗 오류가 발생했다.

오류 로그을 살펴보면

HHH000143: Bytecode enhancement failed because no public, protected or package-private default constructor was found for entity: com.jpastudy.ms.domain.Entity.StoreEntity. Private constructors don't work with runtime proxies!


Food 조회시 Store는 Proxy 객체로 조회 되는데 Store의 접근 권한이 PRIVATE이므로 Proxy 객체 생성하는 로직에서 오류가 발생하였다.


3. Food : (access = AccessLevel.PRIVATE) , Store  : (access = AccessLevel.PROTECTED) : 정상 동작

정상 동작

해당 코드는 정상 작동 한다.

2022-02-06 11:27:07.204 DEBUG 18716 --- [           main] org.hibernate.SQL                        : 
    select
        foodentity0_.food_id as food_id1_0_0_,
        foodentity0_.food_calorie as food_cal2_0_0_,
        foodentity0_.food_name as food_nam3_0_0_,
        foodentity0_.store_id as store_id4_0_0_ 
    from
        tb_test_food foodentity0_ 
    where
        foodentity0_.food_id=?
2022-02-06 11:27:07.245  INFO 18716 --- [           main] p6spy                                    : #1644114427245 | took 17ms | statement | connection 2| url jdbc:mysql://localhost/test?serverTimezone=UTC
select foodentity0_.food_id as food_id1_0_0_, foodentity0_.food_calorie as food_cal2_0_0_, foodentity0_.food_name as food_nam3_0_0_, foodentity0_.store_id as store_id4_0_0_ from tb_test_food foodentity0_ where foodentity0_.food_id=?
select foodentity0_.food_id as food_id1_0_0_, foodentity0_.food_calorie as food_cal2_0_0_, foodentity0_.food_name as food_nam3_0_0_, foodentity0_.store_id as store_id4_0_0_ from tb_test_food foodentity0_ where foodentity0_.food_id=5;
======= 쿼리 전송 =======
Food Proxy ? Entity : class com.jpastudy.ms.domain.Entity.FoodEntity  // 실제 Entity 객체
Food ID : 5
Food Name : 항정살
Food Calorie : 500
Store Proxy ? Entity : class com.jpastudy.ms.domain.Entity.StoreEntity$HibernateProxy$3YCd837F
// Proxy 객체

그 이유는 Food는 em.find를 통해 실제 Entity 객체로 조회 되었기 때문이다. 그리고 Store는 Protected이므로 정상적으로 Proxy 객체가 생성된 것을 확인할 수 있다.


4. Food와 Store 모두 (access = AccessLevel.PRIVATE) : 오류 발생

 

Food는 실제 Entity 객체가 생성되고 조회 쿼리가 발생하였으나 Store는 Private 선언으로 Proxy 객체 생성에 오류가 발생하였다.



그렇다면 궁금한 것 하나 Food 또한 Proxy로 조회하는 getReference를 활용하면 어떻게 될까?

FoodEntity foodEntity = em.getReference(FoodEntity.class,5L); // food_id 값이 5L인 데이터를 찾는다.

 

오류 발생

당연하게도 Food 또한 Proxy 객체 생성에 오류가 발생한다.

 


마지막으로 테스트 하면서 의문이 들어 하나의 테스트 케이스를 추가해보자.

5. Food와 Store 모두 (access = AccessLevel.PRIVATE) 로 조회하지만 Proxy가 아닌 실제 Entity 객체로 조회한다면 어떻게 될까? 즉,  EAGER (즉시로딩)

  • @ManyToOne(fetch = FetchType.EAGER)
// Food Entity 클래스

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "store_id")
public StoreEntity storeEntity;

정상동작

 

즉시 로딩일 경우 Proxy 객체가 생성되는 것이 아닌 Entity를 바로 조회하기 때문에 오류가 발생하지 않는다.


이번 테스트를 통해 Entity의 access = AccessLevel 은 Proxy와 관련이 되어 있다는 것을 알 수 있었다. 물론 Public으로 설정시에도 Proxy 객체 생성이 가능하지만 Entity 외부 접근을 차단하는 Protected를 활용하는 것이 안정성 측면에서 더 낫다.



끝.

예시코드는 다음 레포지토리에 있으며 차근 차근 채워나갈 예정이다.

https://github.com/pminsu01/JPAStudy

 

GitHub - pminsu01/JPAStudy: JPA Study Repository

JPA Study Repository. Contribute to pminsu01/JPAStudy development by creating an account on GitHub.

github.com

 

728x90

Entity에서 참조할 때 No Argument Constructor 의 경우에 참조가능한 범위가 있다. 특히 이 경우에 AccessLevel 을 Package 단계로 설정해두면 빨간맛을 뱉는데, 물론 Compile 자체에는 문제가 없을지라도 빨간맛을 보기 싫다면 변경하면 된다.

 

@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@Builder(toBuilder = true)
@Table(name = "batch_user_emails")

 

이걸

@NoArgsConstructor(access = AccessLevel.PUBLIC)

Public 단계로 바꿔주면 된다.

 

에러를 그대로 해석하면 되는 문제다.

 

아래는 다른 블로그에서 찾아온 기본 맛에 대한 글

@NoArgsConstructor

기본 사용법은 다음과 같습니다.

@NoArgsConstructor
public class BookWithLombok {

    private Long id;
    private String isbn;
    private String name;
    private String author;
}

자바로 표현하면 다음과 같습니다.

public class BookWithOutLombok {

    private Long id;
    private String isbn;
    private String name;
    private String author;

    public BookWithOutLombok() {

    }
}

@AllArgsConstructor

기본 사용법은 다음과 같습니다.

@AllArgsConstructor
public class BookWithLombok {

    private Long id;
    private String isbn;
    private String name;
    private String author;
    private boolean useYn;
}

자바로 표현하면 다음과 같습니다.

public class BookWithLombok {
    private Long id;
    private String isbn;
    private String name;
    private String author;
    private boolean useYn;

    public BookWithLombok(final Long id, final String isbn, final String name, final String author, final boolean useYn) {
        this.id = id;
        this.isbn = isbn;
        this.name = name;
        this.author = author;
        this.useYn = useYn;
    }
}

@RequiredArgsConstructor

기본 사용법은 다음과 같습니다.

@RequiredArgsConstructor
public class BookWithLombok {

    private final Long id;
    private final String isbn;
    private final String name;
    private final String author;
    private boolean useYn;
}

자바로 표현하면 다음과 같습니다.

public class BookWithLombok {
    private final Long id;
    private final String isbn;
    private final String name;
    private final String author;
    private boolean useYn;

    public BookWithLombok(final Long id, final String isbn, final String name, final String author) {
        this.id = id;
        this.isbn = isbn;
        this.name = name;
        this.author = author;
    }
}

 

 

access - 접근제한자

생성자의 대해서 접근제한자를 지정할 수 있습니다. 기본 접근제한자는 public 입니다.
접근제한자 목록은 다음과 같습니다.

PUBLIC

모든 곳에서 접근 가능합니다.
다음과 같이 사용할 수 있습니다.

@NoArgsConstructor(access = AccessLevel.PUBLIC)

자바로 표현하면 다음과 같습니다.

public class BookWithLombok {
    private Long id;
    private String isbn;
    private String name;
    private String author;

    public BookWithLombok() {
    }
}

MODULE

같은 패키지내에서 접근 가능합니다.
다음과 같이 사용할 수 있습니다.

@NoArgsConstructor(access = AccessLevel.MODULE)

자바로 표현하면 다음과 같습니다.
default 와 동일하며 같은 Lombok에서는 package 와 동일합니다.

public class BookWithLombok { 
    private Long id; 
    private String isbn; 
    private String name; 
    private String author; 

    BookWithLombok() { 
    } 
}

PROTECTED

같은 패키지 또는 자식 클래스에서 사용할 수 있습니다.
다음과 같이 사용할 수 있습니다.

@NoArgsConstructor(access = AccessLevel.PROCTECTED)

자바로 표현하면 다음과 같습니다.

public class BookWithLombok {
    private Long id;
    private String isbn;
    private String name;
    private String author;

    protected BookWithLombok() {
    }
}

PACKAGE

같은 패키지안에서 접근 가능하며 MODULE 과 동일한 기능을 합니다.
다음과 같이 사용할 수 있습니다.

@NoArgsConstructor(access = AccessLevel.PACKAGE)

자바로 표현하면 다음과 같습니다.

public class BookWithLombok {
    private Long id;
    private String isbn;
    private String name;
    private String author;

    BookWithLombok() {
    }
}

PRIVATE

내부 클래스에서만 사용할 수 있습니다.
다음과 같이 사용할 수 있습니다.

@NoArgsConstructor(access = AccessLevel.PRIVATE)

자바로 표현하면 다음과 같습니다.

public class BookWithLombok {
    private Long id;
    private String isbn;
    private String name;
    private String author;

    private BookWithLombok() {
    }
}

NONE

기본값인 PUBLIC 과 동일합니다.
다음과 같이 사용할 수 있습니다.

@NoArgsConstructor(access = AccessLevel.NONE)

자바로 표현하면 다음과 같습니다.

public class BookWithLombok {
    private Long id;
    private String isbn;
    private String name;
    private String author;

    public BookWithLombok() {
    }
}

출처: https://lovethefeel.tistory.com/71 [사는 이야기:티스토리]

728x90

 

 

말 그대로 import 구문을 빠트렸을 때 발생할 수 있는 상태이다. 일반적으로는 assertion 을 좀더 가독성을 늘리기 위해서 Hamcrest matcher 와 사용되곤 하는데 JUnit 에 들어있다. 

 

또한 Spring Boot test starter 에 의존성을 가진다

 

 

상단부에서 라이브러리를 납치해준다. IntelliJ 에서 import 하고 싶다고 마우스를 댓다간 못찾는 사태가 있다

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;

 

 

 

JUnit 5(JUnit Jupiter)를 사용하는 경우에는 대게 JUnit 5의 Assertion 을 사용하고, 이 경우에는 직접적으로 assertThat method를 포함시키진 않는다.

 

하쥐만 Hamcrest matcher 를 import 구문을 상단에 포함시킴으로써 같이 사용할 수 있따.

 

예시

@Test
public void shouldLoginUserSuccessfully() throws Exception {
    // ... setup for mockMvc.perform ...

    MvcResult result = mockMvc.perform(/* your mockMvc perform call */).andReturn();
    String responseBody = result.getResponse().getContentAsString();

    // Use assertThat with a Hamcrest matcher
    assertThat(responseBody, containsString("expectedToken"));
}

 

 

취향껏 추가해보자

JUnit 5를 사용하고 native assertion library 사용에서 말뚝을 박고 싶은 경우에는 Assertion.assertTrue 를 String.contains 와 합쳐서 쓸 수 있다.

 

import org.junit.jupiter.api.Assertions;

// Inside your test method
Assertions.assertTrue(responseBody.contains("expectedToken"), "Response body does not contain expected token");
728x90
        // Generate JWT token
        return Jwts.builder()
                .setSubject(user.getUserId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24 hours expiration
                .signWith(SignatureAlgorithm.HS512, "YourSecretKey") // Replace 'YourSecretKey' with your actual secret key
                .compact();

 

 

io.jsonwebtoken library 안에서 signWith (SignatureAlgorithm, String) 라는 놈은 이제 Deprecated 된 놈 중 하나인데 보안적인 이유때문에 짜진 친구이다.

 

이제는 String 대신에 Key 하나를 던져서 보안성을 강화해보자

 

 

Key 를 사용하기 위해 Library 2개를 더 납치해준다

import javax.crypto.SecretKey;
import io.jsonwebtoken.security.Keys;
@Service
public class AuthService {

    @Autowired
    private UserRepository userRepository;

    private final SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512); // Securely generate a key

    public String authenticateAndGenerateToken(LoginDto loginDto) {
        User user = userRepository.findByUserId(loginDto.getUserId());

        if (user == null || !new BCryptPasswordEncoder().matches(loginDto.getPassword(), user.getPassword())) {
            throw new IllegalArgumentException("Invalid credentials");
        }

        return Jwts.builder()
                .setSubject(user.getUserId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24 hours expiration
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
    }
}

 

 

+ Recent posts