java Spring JpaRepository 尚未保存嵌套对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12897089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested objects have not been saved by Spring JpaRepository
提问by Tony Skulk
I have a Spring Roo application with GWT. On server-side I′ve got simple JpaRepository interfaces for all entities like:
我有一个带有 GWT 的 Spring Roo 应用程序。在服务器端,我为所有实体提供了简单的 JpaRepository 接口,例如:
@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
有一个与 MyOtherEntity 类具有一对一关系的 MyEntity 类。当我调用我的实体服务持久方法时
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
只会保存 myEntity 对象。MyEntity 的所有子对象都将被忽略。将 myEntity 对象与 myOtherEntity 对象一起保存的唯一方法是调用
myOtherEntityRepository.save(myOtherEntity);
before the above code. So is there a more elegant way to automatically save sub objects with JpaRepository interface?
在上面的代码之前。那么有没有更优雅的方式来自动保存带有 JpaRepository 接口的子对象呢?
回答by Zaw Than oo
I don't know your implementation details. But, I think, it just need to use CascadeType
in JPA
. JPA Reference CascadeType.
我不知道你的实现细节。但是,我认为,它只需要CascadeType
在JPA
. JPA 参考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
对于递归 MyEntity 关系
public class MyEntity {
@OneToOne(cascade=CascadeType.PERSIST) <or> @OneToOne(cascade=CascadeType.ALL) <-- for all operation
@JoinColumn(name = "YOUR-ID")
private MyEntity myEntity ;
}