tags:

views:

321

answers:

1

Hi, I have a eneity:

@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 + attribute2;
  }
  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?

A: 

After a little search ,problem is solved by EntityListeners, here is my solution:

http://www.ke-cai.net/2010/01/jpa-one-to-many-persist-children-with.html

Ke CAI