简体   繁体   中英

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.

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. Is it possible to use cascade to update it?

First of all, you have to persist any attached objects withint a @Transactional . Then you must fetch the child, and if it exists assign the existing child to A , otherwise create a new one.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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