woniper

[JPA] @OneToMany / @ManyToOne, 1:N / N:1 관계 매핑 본문

Framework

[JPA] @OneToMany / @ManyToOne, 1:N / N:1 관계 매핑

Woniper 2015.05.12 01:42
  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_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();
	}

}


0 Comments
댓글쓰기 폼