woniper

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

Framework

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

Woniper 2015.05.12 01:47
  1. JPA란 무엇인가?
  2. JavaSE 환경에서 JPA 설정 및 CRUD
  3. JavaEE 환경(Spring)에서 JPA 설정 및 CRUD
  4. @OneToOne, 1:1 관계 매핑
  5. @OneToMany / @ManyToOne, 1:N / N:1 관계 매핑
  6. @ManyToMany, N:M 관계 매핑
  7. Entity 객체 생명주기(Lifecycle)와 Persistence Context


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


0 Comments
댓글쓰기 폼