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

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

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

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