[JPA] @ManyToMany, N:M 관계 매핑

2020. 9. 7. 12:49 Java 관련/JPA

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();
    }
}

출처 : https://blog.woniper.net/265?category=531455