开发者

jpa one-to-many persist children with its ID

@Entity public class Item {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column
 private Long id;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "item")
 private List<Feature> features= new ArrayList<Feature>();

The Children Entity:

public class Feature{
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private Long id;

 private String attribute1;
 private String attribute2;
 private String featureCode;

    @ManyToOne
 private Item item;

        .....
 public String getFeatureCode() {
  if (item != null) {
   feature = item.getId() + attribute1 + att开发者_JS百科ribute2;
  }
  return feature;
 }

You can see from my annotaiton, When Item pesist, it will also persist its children.

As composited ID has a very bad reputation and I realy need its parent's ID in the Feature in order to easy query, I add an featureCode to append the three column together.

My problem is , the Item's id is generated from database. From the debug information, I guess it same Item first, then update Feature's item. This causes my featureCode's item.getId() null result.

Is it possible to change one-to-many's cascade persist behavoir, like persist Item first, then save it's children?


Your issue is most likely that you are using IDENTITY id generation (AUTO). Instead use TABLE or SEQUENCE, then your ids can be preallocated, and you will have access to the Item's id at persist instead of only after insert.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜