Entity의 User ,Todo, Reply, Manager 연관관계 생성하기
Todo와 Reply는 1:N 연관
User와 Todo는 N:M 관계 , 중간에 Manager Entity생성하여 각각 연결해주기
User
@Entity
@Getter
@NoArgsConstructor
public class User extends Timestamped {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userName;
@Column(unique = true)
private String email;
public User(String userName, String email) {
this.userName = userName;
this.email = email;
}
}
Todo
@Entity
@Getter
@NoArgsConstructor
public class Todo extends Timestamped {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String contents;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id",nullable = false)
private User user;
@OneToMany(mappedBy = "todo",cascade = CascadeType.REMOVE)
private List<Reply> replys = new ArrayList<>();
public Todo(User user , String title, String contents){
this.user = user;
this.title = title;
this.contents = contents;
}
public void updateTitle(String title){
this.title = title;
}
public void updateContents(String contents){
this.contents = contents;
}
}
Reply
@Entity
@Getter
@NoArgsConstructor
public class Reply extends Timestamped { //todo와 1 대 N 관계
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "reply_id")
private Long id;
private String contents;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "User_id",nullable = false)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "Todo_id",nullable = false)
private Todo todo;
public Reply(User user, String contents,Todo todo){
this.user = user;
this.contents =contents;
this.todo = todo;
}
public void updateReply(String contents) {
this.contents = contents;
}
}
Manager
@Entity
@Getter
@NoArgsConstructor
public class Manager{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id",nullable = false) //일정 만든사람 id
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "todo_id",nullable = false) //일정 id
private Todo todo;
public Manager(User user, Todo todo) {
this.user = user;
this.todo = todo;
}
}
'java 배우기 > TIL' 카테고리의 다른 글
| 깃허브 브랜치 삭제 반영하기 (0) | 2024.09.03 |
|---|---|
| "Unsuccessful: drop table if exists user cascade" Spring 작동 오류 해결하기 (1) | 2024.08.30 |
| 수준별 강의 복습하기 (1) | 2024.08.29 |
| REST API (0) | 2024.08.28 |
| Spring 배우기 개인과제 (0) | 2024.08.27 |