[JPA] @OneToMany / @ManyToOne, 1:N / N:1 관계 매핑
Table 관계도
Entity
@Entity(name = "tbl_user")
public class User {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;
private String username;
private String nickName;
private String address;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Order> orders;
// getter and setter
public boolean addOrder(Order order) {
if(orders == null)
orders = new ArrayList<>();
return this.orders.add(order);
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", username='" + username + '\'' +
", nickName='" + nickName + '\'' +
", address='" + address + '\'' +
", orders=" + orders +
'}';
}
}
@Entity(name = "tbl_order")
public class Order {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Integer orderId;
private String orderName;
private String note;
private int price;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
public Order() {}
public Order(String orderName, String note, int price, User user) {
this.orderName = orderName;
this.note = note;
this.price = price;
this.user = user;
}
// getter and setter
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", orderName='" + orderName + '\'' +
", note='" + note +
'}' + "\n";
}
}
TEST
public class OneToManyAndManyToOneTest {
@Autowired
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
@Test
public void oneToManyAndManyToOneTest() {
Order order = new Order();
order.setOrderName("test order");
order.setPrice(123);
order.setNote("test note");
User user = new User();
user.setUsername("lkw1989");
user.setNickName("woniper");
user.setAddress("seoul");
// relationship
user.addOrder(order);
order.setUser(user);
entityManager.persist(user);
Assert.assertEquals(user.getOrders().get(0).getOrderId(), order.getOrderId());
}
@Before
public void setUp() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
}
@After
public void after() {
entityManager.getTransaction().commit();
entityManager.close();
}
}
'Java 관련 > JPA' 카테고리의 다른 글
JPA에 기반한 비즈니스로직 중심의 S/W 개발 (0) | 2021.11.17 |
---|---|
JPA 요소 (0) | 2021.10.05 |
[JPA] Entity 객체 생명주기(Lifecycle)와 Persistence Context (0) | 2020.09.07 |
[JPA] @ManyToMany, N:M 관계 매핑 (0) | 2020.09.07 |
[JPA] @OneToOne, 1:1 관계 매핑 (0) | 2020.09.07 |
[JPA] JavaEE 환경(Spring)에서 JPA 설정 및 CRUD (0) | 2020.09.07 |
[JPA] JavaSE 환경에서 JPA 설정 및 CRUD (0) | 2020.09.07 |
[JPA] JPA란 무엇인가? (0) | 2020.09.07 |