简体   繁体   English

使用Spring数据存储库在保存级联中更新子对象会导致ConstraintViolationException

[英]Updating a child object in a save cascade result in ConstraintViolationException using spring data repository

I am new to Spring Data and I want to know how to update the child objects when I save the parent object. 我是Spring Data的新手,我想知道在保存父对象时如何更新子对象。

Pojo: Pojo:

@Entity
@Table(name = "A")
public final class A {
    @Id
    @Column(name = "A_ID")
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "B_ID")
    private B b;        
}

@Entity
@Table(name = "B")
public final class B {

    @Id
    @Column(name = "B_ID")
    private Long id;

    @Column(name = "B_NAME")
    private String bName;  

}

The repository: 仓库:

public interface ARepository extends JpaRepository<A, Long> {
}    

And the unit test: 和单元测试:

@Test
public void testSaveA() {
    B b = new B();
    b.setId(1L);
    b.setName("b");
    A a = new A();
    a.setB(b);

    //If b already exists in database then ConstraintViolationException
    ARepository.save(b);
}

So the issue here is that it's trying to insert b instead of updating it. 因此,这里的问题是它试图插入b而不是对其进行更新。 Is it possible to use cascade to update it? 是否可以使用级联对其进行更新?

First of all, you have to persist any attached objects withint a @Transactional . 首先,您必须在@Transactional保留所有附加对象。 Then you must fetch the child, and if it exists assign the existing child to A , otherwise create a new one. 然后,您必须获取该子项,如果存在,则将现有子项分配给A ,否则创建一个新的子项。

@Transactional()
public void update() {
    B b = ARepository.find(1L);
    if (b == null) b = new B();
    //update etc
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM