model 패키지 생성 후 user, reply, board 클래스를 생성
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, length = 30, unique = true)
private String username;
@Column(nullable = false, length = 100)
private String password;
@Column(nullable = false, length = 50)
private String email;
@CreationTimestamp
private Timestamp createDate;
@Enumerated(EnumType.STRING)
private RoleType role;
//데이터의 범주화를 위해 Enum 타입 사용 권장
@Entity
해당 클래스를 테이블과 매핑한다고 JPA에게 알려준다.
@Entity가 사용된 클래스를 엔티티 클래스라고 합니다.
@Id
해당 변수가 primary key로 사용할 수 있는 식별자 역할을 할 수 있도록 한다.
@GeneratedValue(starategy = GenerationType.IDENTITY)
기본키 매핑 전략을 IDENTITY로 설정.
전략에는 IDENTITY, SEQUENCE, TABLE, AUTO 4가지가 있다.
IDENTITY
키본키 생성을 데이터베이스에 위임하는 전략
프로젝트에 연결된 DB의 넘버링 전략을 따라가겠다는 것.
id값을 null로 하면 알아서 auto_increment 설정 해준다.
SEQUENCE
데이터베이스 Sequence Object 사용
TABLE
키 생성 전용 테이블을 하나 만들어서 데이터베이스 시퀀스를 흉내내는 전략
AUTO
기본 설정 값
방언에 따라 위의 세 가지 전략을 자동으로 지정한다.
@Column(nullable = false, lengh = 30, unique = true)
해당 변수를 컬럼으로 만들고, not null, 길이를 30으로 제한, 같은 데이터는 추가될 수 없다
@CreationTimestamp
해당 컬럼의 기본값을 해당 데이터가 생성된 시각으로 지정
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class Board {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, length = 100)
private String title;
@Lob
private String content;
@ColumnDefault("0")
private int count;
// Many == Board, One == User
// User 조회할 때 Board 즉시 로딩
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "userId")
private User userId;
@CreationTimestamp
private Timestamp createDate;
@OneToMany(mappedBy = "board", fetch = FetchType.EAGER)
private List<Reply> reply;
}
@Lob
DB BLOB, CLOB 타입과 매핑
@ManyToOne(fetch = FetchType.EAGER)
FetchType
JPA가 하나의 엔티티를 조회할 때,
연관관계에 있는 객체들을 어떻게 가져올 것이냐를 나타내는 설정값
EAGER
즉시로딩
데이터를 조회할 때 연관된 모든 객체의 데이터까지 한번에 불러오는 것
LAZY
지연로딩
필요한 시점에 연관된 객체의 데이터를 불러오는 것
@ColumnDefault("'문자열'")
해당 변수를 컬럼으로 만들고, default 값을 user로 설정.
문자열을 인식하기 위해 큰 따옴표 안에 작은 따옴표로 감싸주어야 한다.
@JoinColumn(name ="외래키 이름")
외래키를 매핑할 때 사용한다. name 속성은 매핑할 외래키 이름을 지정한다.
@OneToMany(mappedBy = "board", fetch = FetchType.EAGER)
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class Reply {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, length = 200)
private String content;
@ManyToOne
@JoinColumn(name = "boardId")
private Board board;
@ManyToOne
@JoinColumn(name = "userId") // Reply 테이블의 컬럼명이 된다
private User user;
@CreationTimestamp
private Timestamp createDate;
}
public enum RoleType {
USER, ADMIN
}