[JPA] @ManyToMany, N:M 관계 매핑
Table 관계도
Entity
@Entity(name = "tbl_product")
public class Product {
@Id @GeneratedValue
private int productId;
private String name;
private int price;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "tbl_product_category",
joinColumns = @JoinColumn(name = "product_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<Category> categories;
public Product() {
}
public Product(String name, int price) {
this.name = name;
this.price = price;
}
// getter and setter
public boolean addCategory(Category category) {
if(categories == null)
categories = new ArrayList<>();
return categories.add(category);
}
@Override
public String toString() {
return "Product{" +
"productId=" + productId +
", name='" + name + '\'' +
", price=" + price +
", categories=" + categories +
'}';
}
}
@Entity(name = "tbl_category")
public class Category {
@Id @GeneratedValue
private int categoryId;
private String name;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories")
private List<Product> products;
public Category() {
}
public Category(String name, List<product> products) {
this.name = name;
this.products = products;
}
// getter and setter
public boolean addProduct(Product product) {
if(products == null)
products = new ArrayList<>();
return products.add(product);
}
@Override
public String toString() {
return "Category{" +
"name='" + name + '\'' +
", categoryId=" + categoryId +
'}';
}
}
TEST
public class ManyToManyTest {
@Autowired
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
@Test
public void manyToManyTest() {
Category category = new Category();
category.setName("IT");
entityManager.persist(category);
Product product = new Product();
product.setName("MacBook");
product.setPrice(1000);
product.addCategory(category);
category.addProduct(product);
entityManager.persist(product);
Assert.assertEquals(product.getProductId(), category.getProducts().get(0).getProductId());
}
@Before
public void setUp() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
}
@After
public void after() {
entityManager.getTransaction().commit();
entityManager.close();
}
}
'Java 관련 > JPA' 카테고리의 다른 글
JPA - 엔티티 매니저와 트랜잭션 (0) | 2021.11.17 |
---|---|
JPA에 기반한 비즈니스로직 중심의 S/W 개발 (0) | 2021.11.17 |
JPA 요소 (0) | 2021.10.05 |
[JPA] Entity 객체 생명주기(Lifecycle)와 Persistence Context (0) | 2020.09.07 |
[JPA] @OneToMany / @ManyToOne, 1:N / N:1 관계 매핑 (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 |