Nested objects have not been saved by Spring JpaRepository

13,508

I don't know your implementation details. But, I think, it just need to use CascadeType in JPA. JPA Reference CascadeType.

Try as below.

public class MyEntity {
    @OneToOne(cascade=CascadeType.PERSIST) <or> @OneToOne(cascade=CascadeType.ALL) <-- for all operation
    @JoinColumn(name = "YOUR-ID")
    private MyOtherEntity myOtherEntity ;
}

For Recursiivce MyEntity Relationship

public class MyEntity {
    @OneToOne(cascade=CascadeType.PERSIST) <or> @OneToOne(cascade=CascadeType.ALL) <-- for all operation
    @JoinColumn(name = "YOUR-ID")
    private MyEntity myEntity ;
}
Share:
13,508
Tony Skulk
Author by

Tony Skulk

Updated on June 05, 2022

Comments

  • Tony Skulk
    Tony Skulk almost 2 years

    I have a Spring Roo application with GWT. On server-side I´ve got simple JpaRepository interfaces for all entities like:

    @Repository
    public interface MyEntityRepository extends JpaSpecificationExecutor<MyEntity>, JpaRepository<MyEntity, Long> {
    }
    

    There is a MyEntity class that has a One-To-One relationship to a MyOtherEntity class. When I call my entity-service persist method

    public void saveMyEntity (MyEntity myEntity) {
        myEntityRepository.save(myEntity);
    }
    

    only the myEntity object will be saved. All sub objects of MyEntity are ignored. The only way to save the myEntity object along with the myOtherEntity object is calling

        myOtherEntityRepository.save(myOtherEntity);
    

    before the above code. So is there a more elegant way to automatically save sub objects with JpaRepository interface?