1

I have a bidirectional entity similar like the one in hibernate example: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association

@Entity
public class Troop {
    @OneToMany
    @JoinColumn(name="troop_fk") //we need to duplicate the physical information
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk", insertable=false, updatable=false)
    public Troop getTroop() {
    ...
}

Now I need save all the records into 2 tables through a JSON like this:

{
  "TroopName": "ABC", 
  "Soldiers": [{"Name":"Jack", "Age": "40"}, {"Name":"TOM", "Age": "30"}]
}

It will insert 1 record in the troop table and 2 records in soldier table which works fine. The only problem is in the soldier the foreign key is missing. I think it might relate to the troop.Id is not generated when the soldier table get populated. How can I populate this id to the soldier then?

I am using spring mvc + spring roo + json support

4

1 回答 1

0

自我回答:问题是 Spring Roo 生成 AspectJ 代码来设置士兵而不设置反向引用(尽管我已经指定它是双向关系)。所以我必须自己添加它。

public void Troop.setSoldiers(Set<Soldier> soldiers) {
    this.soldiers= soldiers;  // spring roo only generate this line!

    // I add the following segment:
    for(Soldier soldier: soldiers) {
        soldier.setTroop(this);
    }
}
于 2013-04-03T02:52:06.343 回答