1:1 관계
- 단방향
@OneToOne
외래키의 주인을 직접 설정
음식과 고객이 1:1의 경우
주인은 @JoinColumn 사용
음식 (외래키의 주인)
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
@OneToOne
@JoinColumn(name = "user_id")
private User user;
}
고객
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
- 양방향
주인은 @JoinColumn사용
고객은 mappedBy 사용
음식(주인)
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
@OneToOne
@JoinColumn(name = "user_id")
private User user;
}
고객
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(mappedBy = "user")
private Food food;
}
N:1 관계
@ManyToOne 에너테이션 사용
- 단방향
음식 (N이고 주인일때)
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
고객
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
-양방향
음식(N)
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
고객
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "user")
private List<Food> foodList = new ArrayList<>();
}
1:N 관계
- 단방향
음식(주인)
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
@OneToMany
@JoinColumn(name = "food_id") // users 테이블에 food_id 컬럼
private List<User> userList = new ArrayList<>();
}
고객
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
'Spring' 카테고리의 다른 글
[TIL] 231113 Spring | 3Layer Architecture, IoC와 DI, Bean (0) | 2023.11.14 |
---|---|
[TIL] 231110 Spring Database연결하기, SQL, JdbcTemplate, JDBC (0) | 2023.11.10 |
[TIL] 231108 Spring 숙련주차 Bean, 인증과 인가, 사용자 관리 (0) | 2023.11.08 |
[TIL] 231106 Spring 과제 (0) | 2023.11.06 |
[TIL] 231103 Spring 입문 (0) | 2023.11.03 |