java jpa自身关联_JPA的一对多映射(双向)关联

public classJPATest {privateEntityManagerFactory entityManagerFactory;privateEntityManager entityManager;privateEntityTransaction transaction;

@Beforepublic voidinit(){

entityManagerFactory= Persistence.createEntityManagerFactory("jpa-1");

entityManager=entityManagerFactory.createEntityManager();

transaction=entityManager.getTransaction();

transaction.begin();//开启事务

}

@Afterpublic voiddestroy(){

transaction.commit();

entityManager.close();

entityManagerFactory.close();

}//修改

@Testpublic voidtestUpdate(){

Customer customer=entityManager.find(Customer.class, 4);

customer.getOrders().iterator().next().setOrderName("O-XXX-10");

}//删除//默认情况下,若删除1的一端,则会先把关联的多的一段的外键置空,然后删除一的一端

可以通过@OneToMany的cascade 属性来修改默认的删除策略

@Testpublic voidtestOneToManyRemove(){

Customer customer=entityManager.find(Customer.class, 7);

entityManager.remove(customer);

}//默认对关联多的一方使用懒加载的加载策略(延迟加载)//可以使用@OneToMany的fetch 属性来修改默认的加载策略//查询

@Testpublic voidtestOneToManyFind(){

Customer customer=entityManager.find(Customer.class,6);

System.out.println(customer.getLastName());

System.out.println(customer.getOrders().size());

}//双向一对多的关联关系在执行保存时//若先保存多的一端,在保存一的一端,默认情况下,会多出四条update语句//若先保存一的一端则会多出2(n)条update语句//在进行双向一对多的关联关系时,建议使用多的一方来维护关联关系,而1的一方不维护关联关系,这样会有效的减少sql语句

//注意:若在一的一端@oneToMany 中使用mapperBy属性,则@oneToMany端就不能在使用@JoinColumn(name="CUSTOMER_ID")属性//保存

@Testpublic voidtestOneToManyPersist(){

Customer customer=newCustomer();

customer.setAge(16);

customer.setBirth(newDate());

customer.setCreatedTime(newDate());

customer.setEmail("CC@163.com");

customer.setLastName("AA");

Order order1=newOrder();

order1.setOrderName("o-CC-1");

Order order2=newOrder();

order2.setOrderName("o-CC-2");//建立关联关系

customer.getOrders().add(order1);

customer.getOrders().add(order2);//执行保存操作

entityManager.persist(customer);

entityManager.persist(order1);

entityManager.persist(order2);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值