JPA对象映射不会在插入时保存子项

时间:2012-07-23 06:48:21

标签: oracle jpa playframework

我的Play应用程序上有这个模型。

@Entity
@Table(name="SHOPPER")
public class User extends GenericModel {

    ...

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "SASHNBR", insertable = true, updatable = true)
    public List<Direction> directions;
}

方向模型看起来像这样

@Entity
@Table(name="SHADDR")
public class Direccion extends GenericModel {

    ...

    @Column(name="SASHNBR")
    @Required
    public Long idUser;
}

这样我就出错了,因为Direction在保存时没有生成idUser。

我也是这样试过的。

@Entity
@Table(name="SHOPPER")
public class User extends GenericModel {

    ...

    @OneToMany(cascade = CascadeType.ALL, mappedBy="user")
    public List<Direction> directions;
}

方向模型看起来像这样

@Entity
@Table(name="SHADDR")
public class Direccion extends GenericModel {

    ...

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "SASHNBR", insertable = true, updatable = true)
    User user;
}

但它也没有用。

有人可以帮我这个吗?

谢谢! :)

2 个答案:

答案 0 :(得分:2)

你需要自己保护孩子。您可以查看tutorial作为示例。

public User addDirection(Direction direction) {    
    this.directions.add(direction);
    this.save();
    return this;
}

@Override
public User save(){
    for (Direction dir : directions) {
        dir.save()
    }
    super.save()
    return this;
}

答案 1 :(得分:1)

请尝试这样的事情:

User user = new User();
// [...] call required setters of user object
for (int i=0; i<5; i++) {
    Direction direction = new Direction();
    direction.setUser(user);
    // [...] call other required setters of direction object
    user.getDirections().add(direction);
}
entitymanager.persist(user);
相关问题