4

我正在尝试做一个非常简单的删除操作,但不知何故它不起作用,因为我将 DAO 更新为 JpaRepository。基本上是这样的:

A a = aRepository.findOne(id);
a.setSomeField("someNewString");

List<B> bList = a.getBs();
bList.clear();
aRepository.saveAndFlush(a);

该字段按预期更新,但bList保持不变。我什至尝试过:

A a = aRepository.findOne(id);
a.setSomeField("someNewString");

List<B> bList = a.getBs();
for(B b : bList) {
   bRepository.delete(b);
}
bRepository.flush();
bList.clear();
aRepository.saveAndFlush(a);

还是一样...

A 类如下所示:

@Entity
@Table(name = "A")
public class A implements Serializable {
    private static final long serialVersionUID = -1286451120913657028L;

    @Column(name = "id", length = 16, nullable = false, updatable = false)
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @GeneratedValue(generator = "uuid")
    @Basic(fetch = FetchType.EAGER)
    @Id
    protected UUID id;

    @OneToMany(mappedBy = "a", fetch = FetchType.EAGER)
    @Cascade({ CascadeType.ALL })
    List<B> bList;

    // getter + setter
}

我究竟做错了什么?!


B类:

@Entity
@Table(name = "B")
public class B implements Serializable {
    @Column(name = "id", length = 16, nullable = false, updatable = false)
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @GeneratedValue(generator = "uuid")
    @Basic(fetch = FetchType.EAGER)
    @Id
    protected UUID id;

    @ManyToOne(optional = false)
    @JoinColumns({ @JoinColumn(name = "A_id", referencedColumnName = "id", nullable = false) })
    @Valid
    A a;

    // setter + getter
}

Setter 和 getter 都非常简单:

public List<B> getBList() {
    return bList;
}

public void setBList(List<B> bList) {
    this.bList = bList;
}

更多信息:

  • 春天 3.2.2
  • 休眠 4.2.2
  • 春天数据共享 1.5.1
  • 弹簧数据-jpa 1.3.2
4

1 回答 1

12

更新A.bList属性如下:

public class A {
    @OneToMany(mappedBy = "a", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    List<B> bList;
}

annotation 属性将orphanRemoval = true告诉底层 JPA 实现删除没有任何父级的 B 记录。

另外,由于是由B一方管理关联,所以在断开关联时应清除其a属性。为了使这更易于阅读并消除调用者的此类实现细节的负担,您应该在以下位置引入管理方法A

public class A {
    public void clearBList() {
        for (B b : bList) {
            b.releaseA();
        }
        bList.clear();
    }
}

public class B {
    void releaseA() {
        this.a = null;
    }
}

您应该避免直接公开集合,而是返回它的不可变版本,以防止 A 类的客户端在 A 类不知道的情况下直接修改集合。A管理B列表,所以它应该完全控制它!

public class A {
    public List<B> getBList() {
        return Collections.unmodifiableList(bList);
    }
}

希望有帮助。

于 2013-06-18T19:38:14.267 回答