JPA学習ノート-一方向一対多の関連関係をマッピングする
Customerクラス
Orderクラス
テストクラス
この関連方式は推奨されません
@Table(name="jpa_customer")
@Entity
public class Customer {
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
@Id
private Integer id;
@Column(name="last_name")
private String lastName;
private String email;
private int age;
@JoinColumn(name="customer_id")//
@OneToMany(fetch=FetchType.EAGER, cascade={CascadeType.REMOVE})// , 。cascade 。
private Set<Order> orders = new HashSet<>();
// getter setter
}
Orderクラス
@Table(name = "jps_order")
@Entity
public class Order {
@GeneratedValue
@Id
private Integer id;
@Column(name = "order_name")
private String orderName;
// getter setter
}
テストクラス
// , update , n
@Test
public void testOneToManyPersist() {
Customer customer = new Customer();
customer.setAge(23);
customer.setEmail("[email protected]");
customer.setLastName("shang");
Order order1 = new Order();
order1.setOrderName(" 1");
Order order2 = new Order();
order2.setOrderName(" 2");
customer.getOrders().add(order1);
customer.getOrders().add(order2);
entityManager.persist(customer);
entityManager.persist(order1);
entityManager.persist(order2);
}
@Test
public void testOneToManyFind() {
Customer customer = entityManager.find(Customer.class, 1);
System.out.println(customer.getLastName());
System.out.println(customer.getOrders().size());//
}
@Test
public void testOneToManyRemove() {
Customer customer = entityManager.find(Customer.class, 1);
entityManager.remove(customer);// order null, 。 cascade
}
//update
@Test
public void testOneToManyUpdate() {
Customer customer = entityManager.find(Customer.class, 2);
customer.getOrders().iterator().next().setOrderName("new name");
}
この関連方式は推奨されません