【问题标题】:Allow null reference in JPA @ManyToOne relationship (Play! Framework)在 JPA @ManyToOne 关系中允许空引用(播放!框架)
【发布时间】:2012-02-13 17:42:15
【问题描述】:

我对提出这个问题的必要术语有点陌生,但我们会看看我是否能正确回答。

我有一个 JPA 实体,它表示几个其他实体的连接,称为 UserJump:

@Entity
public class UserJump extends Model{

    @ManyToOne
    public User user;
    @ManyToOne
    public JumpSession jumpSession;
    @ManyToOne
    public Parachute parachute;
}

我有一个返回 UserJump 的 JumpSession 类:

@Entity
public class JumpSession extends GenericModel{

    @OneToMany(mappedBy="jumpSession")
    public List<UserJump> userJumps;
}

但是,我需要能够删除 JumpSession 对象,同时保留引用它们的任何 UserJump 对象(现在我在 JumpSession 上调用 delete() 时得到 ConstraintViolationException),因为UserJump 对象仍将其他唯一信息链接在一起。理想情况下,UserJump 中的jumpSession 变量将更改为null

我该怎么做?

【问题讨论】:

    标签: jpa playframework persistence many-to-one


    【解决方案1】:

    您只需要在删除 JumpSession 之前修改 UserJump:

    for (UserJump uj : jumpSession.getUserJumps()) {
        uj.setJumpSession(null); 
        // now the UserJump doesn't reference the soon-to-be-deleted JumpSession anymore
    }
    session.delete(jumpSession);
    

    (注意:上面是传统的Java Hibernate代码。我不知道如何用Play的方式翻译)

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多