DEVLOG

[JPA] 연관관계 매핑 본문

Spring Boot/JPA

[JPA] 연관관계 매핑

BINTHEWORLD 2022. 6. 25. 13:21

ORM(Object Relational Mapping, 객체-관계 매핑)

객체와 관계형 데이터베이스의 데이터자동으로 매핑(연결)해주는 것

@ManyToOne

다대일( N : 1 ) 관계 매핑 정보
연관관계를 매핑할 때 이렇게 다중성을 나타내는 어노테이션(@ManyToMany, @OneToOne 등…)은 필수로 사용해야 하며, 엔티티 자신을 기준으로 다중성을 생각해야 함

@JoinColumn(name="category_no")

@JoinColumn 어노테이션은 외래 키를 매핑 할 때 사용
name 속성에는 매핑 할 외래 키 이름을 지정

@JoinColumn 어노테이션을 생략하면 아래와 같은 전략에 따라 외래 키를 매핑
필드명 + “_” + 참조하는 테이블의 기본 키(@Id) 컬럼명

User.java

@Entity // User클래스가 MySQL에 테이블로 생성된다. 
public class User {
	@Id // PK
	@GeneratedValue(strategy = GenerationType.IDENTITY) // GenerationType : 프로젝트에 연결된 DB의 넘버링 전략을 따라간다. (IDENTITY : 오라클-시퀀스, MySQL-AUTO_INCREMENT)
	private int id; // 비워도 자동으로 INSERT
	
	@Column(nullable = false, length = 30)
	private String username; // 아이디
	
	@Column(nullable = false, length = 100) // ex) 123456 => 해쉬(비밀번호 암호화) 
	private String password;
	
	@Column(nullable = false, length = 50)
	private String email; 
	
	@ColumnDefault("'user'")
	private String role; // Enum을 쓰는 게  좋다. // Admin, User, Manager  
	
	@CreationTimestamp // 시간이 자동 입력 => 비워도 자동으로 INSERT
	private Timestamp createDate; 
}

Board.java

user 테이블의 id를 FK로 사용하기 위해

@Entity
public class Board {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY) // AUTO_INCREMENT
	private int id;
	
	@Column(nullable = false, length = 100)
	private String title; 
	
	@Lob // 대용량 데이터 쓸 때 사용 (MySQL : longtext형)
	private String content; // 섬머노트 라이브러리 <html> 태그가 섞여서 디자인 된다. => 크기 커진다.
	
	@ColumnDefault("0") // int 이므로  홑 따옴표 필요없음
	private int count; // 조회수 
	
	@ManyToOne // Many = Board, One = User : 한 명의 유저는 여러 개의 게시글을 쓸 수있다는 의미
	@JoinColumn(name="userId")
	// FK 만들어짐 
	private User user; // DB는 Object를 저장할 수 없다. FK, Java는 Object를 저장할 수 있다.  
	
	@CreationTimestamp
	private Timestamp createDate; 
	
}
콘솔창

🙆‍♂️출처🙇‍♂️
https://gmlwjd9405.github.io/2019/02/01/orm.html

[DB] ORM이란 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

https://victorydntmd.tistory.com/208

[Spring JPA] 연관관계 매핑

연관관계 매핑 엔티티( Entity )들은 대부분 서로 관계를 맺고 있습니다. 예를들어 Category 엔티티와 Book 엔티티가 있을 때, Category에는 많은 Book을 갖는 관계를 갖고 있습니다. 이렇게 엔티티들이

victorydntmd.tistory.com

'Spring Boot > JPA' 카테고리의 다른 글

[JPA] not null constraint violation 에러  (0) 2022.11.16
[JPA] open-in-view  (0) 2022.06.30
[JPA] 페이징  (0) 2022.06.27
[JPA] UPDATE  (0) 2022.06.27
[JPA] SELECT  (0) 2022.06.27
Comments