User 엔티티와 일대다 관계로 Post 엔티티 생성

Soo·2024년 4월 2일

User 엔티티와 일대다관계를 맺을 Post 엔티티를 생성합니다.

Post

  • 아이디
  • 설명
  • User 객체
package study.rest.webservices.restfulwebservices.user;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;

@Entity
public class Post {

    @Id
    @GeneratedValue
    private Integer id;

    private String description;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnore
    private User user;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Post{" +
                "id=" + id +
                ", description='" + description + '\'' +
                '}';
    }
}

한 사람이 여러 포스트 작성이 가능하기 때문에 @ManyToOne을 사용합니다.

중요한점은 xToOne은 기본적으로 fetch가 EAGER로 설정되어있기 때문에 예상하지 못한 쿼리를 발생시킬 수 있습니다.

xToOne을 사용할 때는 항상 fetch 옵션을 LAZY로 변경해 주어야 합니다.

User

  • 여러 포스트를 가지기 때문에 List를 사용해서 Post 객체를 가집니다.
package study.rest.webservices.restfulwebservices.user;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.validation.constraints.Past;
import jakarta.validation.constraints.Size;

import java.time.LocalDate;
import java.util.List;

@Entity(name = "user_details")
public class User {

    @Id @GeneratedValue
    private Integer id;

    @Size(min = 2, message = "이름은 최소 2글자 이상이어야 합니다.")
//    @JsonProperty("user_name")
    private String name;

    @Past(message = "생일의 날짜는 과거여야 합니다.")
//    @JsonProperty("birth_date")
    private LocalDate birthDate;

    @OneToMany(mappedBy = "user")
    @JsonIgnore
    private List<Post> posts;

    protected User() {
    }

    public User(Integer id, String name, LocalDate birthDate) {
        this.id = id;
        this.name = name;
        this.birthDate = birthDate;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthDate=" + birthDate +
                '}';
    }
}

보통 일대다, 다대일 관계에서 연관관계 주인은 “다” 쪽에 있기 때문에 mappedBy 속성을 사용해서 Post 객체의 user 속성에 의해 관리 된다는 것을 표현합니다.

data.sql

  • post 테이블에 데이터 추가
insert into post(id, description, user_id) values (20001, 'AWS 배우기', 10001);
insert into post(id, description, user_id) values (20002, 'Docker 배우기', 10001);
insert into post(id, description, user_id) values (20003, 'Linux 배우기', 10002);
insert into post(id, description, user_id) values (20004, 'DevOps 배우기', 10002);

0개의 댓글