Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JAVA] Record와 DTO #22

Open
jaeuk520 opened this issue Mar 3, 2024 · 1 comment
Open

[JAVA] Record와 DTO #22

jaeuk520 opened this issue Mar 3, 2024 · 1 comment
Labels
공부 정리 ✏️ 개인적으로 찾아보며 정리한 내용

Comments

@jaeuk520
Copy link
Contributor

jaeuk520 commented Mar 3, 2024

Record

Feature

  • 멤버변수는 private final로 선언된다.
  • 필드별 getter가 자동으로 생성된다.
    • getter를 사용할 때는 get_() 이 아닌 필드명, 즉 컴포넌트의 이름만 사용하면 된다. ex. name()
  • 모든 멤버변수를 인자로 하는 public 생성자를 자동으로 생성한다.
  • equals, hashcode, toString을 자동으로 생성한다.
  • 기본생성자는 제공하지 않으므로 필요한 경우 직접 생성한다.

보일러 플레이트 코드를 줄일 수 있다!

보일러 플레이트 코드

  • 최소한의 변경으로 여러 곳에서 재사용되면서 반복적으로 비슷한 형태를 가지고 있는 코드 (ex. getter, setter, equals, hashCode, toString 등)

Record를 Entity에는 적용하지 못하는 이유

  • hibernate와 같은 jpa는 프록시 생성을 위해 인수 생성자, non-final 필드, setter 및 non-final 클래스가 없는 엔티티에 의존한다.

즉 프록시를 생성하기 위해서 entity는 불변이면 안 된다!

  • 쿼리 결과를 매핑할 때 객체를 인스턴스화 할 수 있도록 매개변수가 없는 생성자가 필요하다.

    • record는 매개변수가 없는 생성자를 제공하지 않는다. (record는 불변 객체이기 때문에 setter를 사용할 수 없으며 이로 인해 모든 필드의 값을 입력한 후에 생성할 수 있다.)
  • getter가 필수 명명 규칙을 따르지 않는다.

    • 쿼리 결과 처리 후 수행할 getter, setter에 접근할 수 없다.

JPA Entity의 기본 생성자가 필수인 이유:

Reflection API:


Record를 DTO에 적용해보자

record는 한 번 값이 정해지고 나면 setter를 통해 값을 변경할 수 없는데, 자바 내부에서 데이터 가공 시 중간에 변질될 우려가 없다!



출처: https://velog.io/@power0080/java%EC%9E%90%EB%B0%94-record%EB%A5%BC-entity%EB%A1%9C#1-2-2-record-%ED%8A%B9%EC%A7%95

@david-parkk
Copy link
Member

public record ApiResponse<T>(Boolean isSuccess, int code, String message,
                             @JsonProperty(value = "response") T response,
                             @JsonProperty(value = "errorResponse") ErrorResponse errorResponse) {
}

record를 활용해서 response 를 만들어도 좋을것 같네요

@jaeuk520 jaeuk520 added the 공부 정리 ✏️ 개인적으로 찾아보며 정리한 내용 label Mar 11, 2024
@jaeuk520 jaeuk520 changed the title 🧷 Record와 DTO [JAVA] Record와 DTO Mar 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
공부 정리 ✏️ 개인적으로 찾아보며 정리한 내용
Projects
None yet
Development

No branches or pull requests

2 participants