jpa怎么实现新增获取id_JPA从父级合并但创建子级时,如何获取生成的ID /对象?...

I have an entity that has been previously persited and has a @OneToMany relationship with another entity. In order to add a new entity I just add my new entity in the managed object and use cascadeType.ALL to persist the changes. Is there a way that I can get the id's of the newly created objects or get the original (unmanaged) object I used with the merge to have its id updated?

In pseudo-code I would expect the following to happen:

New copy is going to be returned for merged entity

Old copy is going to be update for new entities

Example:

Parent A, id=13

Child B, id=0

In essence, I want to issue a merge on the parent but cascade persist on child (so that the original child instance is updated, not copied).

Obviously this doesn't happen.

I am using hibernate as the provider.

解决方案

Stackoverflow post and JPA documentation have the answer provided that you do your research.

The way to do what I want is to use persist on the managed parent. This will ignore any changes on the parent, but will cascade persist (provided that it is set up to cascade). The child object will have the correct id afterwards.

....

JPAEntity newObject=new JPAEntity();

managedObject.addChild(newObject);

em.persist(managedObject)

newObject.getId() //work fine!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值