JpaRepository删除子元素

时间:2013-06-18 18:13:40

标签: spring hibernate list jpa repository

我正在尝试进行一个非常简单的删除操作,但是由于我将DAO更新为JpaRepository,因此它无法正常工作。基本上是这样的:

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

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

字段get按预期更新,但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;
}

更多信息:

  • spring 3.2.2
  • hibernate 4.2.2
  • spring-data-commons 1.5.1
  • spring-data-jpa 1.3.2

1 个答案:

答案 0 :(得分:9)

更新A.bList属性,如下所示:

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

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);
    }
}

希望有所帮助。