以Customer表和Contact表为例:
新增:
//一对多增加
@Test
public void testPersist() {
Customer customer = new Customer();
customer.setName("新客户");
Contact contact = new Contact();
contact.setName("新联系人");
//添加双向关联关系
customer.getContacts().add(contact);
contact.setCustomer(customer);
EntityManager em = MyJPAUtils.getEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(customer);//我已经在客户上配置了级联属性,所以这里直接保存customer即可
tx.commit();
em.close();
}
更新:
//一对多更新
@Test
public void testMerge() {
Contact contact = new Contact();
contact.setName("联系人4");
EntityManager em = MyJPAUtils.getEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Customer customer = em.find(Customer.class, Integer.parseInt("1"));
customer.ge