Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested objects have not been saved by Spring JpaRepository

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?

like image 610
Tony Skulk Avatar asked Oct 15 '12 13:10

Tony Skulk


1 Answers

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 ;
}
like image 71
Zaw Than oo Avatar answered Oct 15 '22 05:10

Zaw Than oo