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;
// getter setter
}
Orderクラス
@Table(name = "jps_order")
@Entity
public class Order {
@GeneratedValue
@Id
private Integer id;
@Column(name = "order_name")
private String orderName;
@JoinColumn(name = "customer_id")
//
@ManyToOne(fetch=FetchType.LAZY)//
//
private Customer customer;
// getter setter
}
テスト
// , 1, n。 update
@Test
public void testManyToOnePersist() {
Customer customer = entityManager.find(Customer.class, 6);
Order order1 = new Order();
order1.setOrderName(" 1");
order1.setCustomer(customer);
Order order2 = new Order();
order2.setOrderName(" 2");
order2.setCustomer(customer);
entityManager.persist(order1);
entityManager.persist(order2);
}
// n 1
@Test
public void manyToOneFind() {
Order order = entityManager.find(Order.class, 1);
Customer customer = order.getCustomer();
System.out.println(customer);
}
@Test
public void manyToOneRemove() {
Order order = entityManager.find(Order.class, 1);
//entityManager.remove(order);//
Customer customer = order.getCustomer();
// entityManager.remove(customer);// ,
}
@Test
public void manyToOneUpdate() {
Order order = entityManager.find(Order.class, 1);
order.getCustomer().setLastName("new name");
//commit update
}