엔티티 정의 (작가 - 책)
@Entity
@NoArgsConstructor
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class Author extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String country;
@ManyToMany
private List<Book> books = new ArrayList<>();
}
@Entity
@NoArgsConstructor
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class Book extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/*
생략
*/
@ManyToMany
private List<Author> authors = new ArrayList<>();
}
DDL 생성 로그
중간 매핑 테이블 생성
Hibernate :
create table author_books (
author_id bigint not null,
books_id bigint not null
)
다른 예제 - 중간 테이블(매핑 테이블)을 직접 엔티티로 만들기
@JoinTable 없이 N:M 관계를 구현하려면 중간 테이블(매핑 테이블)을 직접 엔티티로 만들어, 2개의 N:1 or 1:N 관계로 구현해야 한다.
User - Order(중간 테이블을 대신하는 엔티티/user_products) - Product
장점
- 중간 테이블에 추가 컬럼을 넣을 수 있음
- 쿼리 및 연관관계 제어가 더 명확해짐
- 성능이나 JPA 캐시 관리 측면에서도 이점이 있음
@Entity
@NoArgsConstructor
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class BookAndAuthor extend BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Book book;
@ManyToOne
private Author author;
}
@Entity
@NoArgsConstructor
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class Book extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/*
생략
*/
@OneToMany
@JoinColumn(name = "book_id")
@ToString.Exclude
private List<BookAndAuthor> bookAndAuthors = new ArrayList<>();
}
@Entity
@NoArgsConstructor
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class Author extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String country;
@OneToMany
@JoinColumn(name = "author_id")
@ToString.Exclude
private List<BookAndAuthor> bookAndAuthors = new ArrayList<>();
}
DDL 생성 로그
Hibernate :
create table book_and_author (
id bigint generated by default as identity,
created_at timestamp,
updated_at timestamp,
author_id bigint,
book_id bigint,
primary key (id)
)
'Spring' 카테고리의 다른 글
| JPA - N:1 연관 관계 (1) | 2025.07.18 |
|---|---|
| JPA - 1:N 연관 관계 (0) | 2025.06.16 |
| JPA - 1:1 연관 관계 (0) | 2025.06.16 |
| JPA - Entity Listener의 활용 (1) | 2025.06.12 |
| JPA (1) | 2025.06.06 |





