org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: sys.entity.Role; nested exception is org.hibernate.PersistentObjectException: 的解决方案
1、错误信息
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: sys.entity.Role; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: sys.entity.Role
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:280)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:225)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy49.save(Unknown Source)
at sys.service.impl.UserServiceImpl.save(UserServiceImpl.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy50.save(Unknown Source)
at sys.test.Test1.test6(Test1.java:151)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: sys.entity.Role
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:97)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:379)
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:319)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:296)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:470)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:295)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:293)
at com.sun.proxy.$Proxy38.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:439)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 51 more
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: sys.entity.Role; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: sys.entity.Role |
2、错误原因。
在多对多保存测试的过程中,常常会出现以上错误信息,出现错误信息的原因是id值没有传进去,需要手动赋值。
如User和Role两个类是多对多关系,Role是维护端,User是维护端,具体代码:
package sys.entity; import java.io.Serializable;
import java.util.HashSet;
import java.util.Set; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Table(name="a_role")
@Entity
public class Role implements Serializable{
private Integer id;
private String roleName;
private Set<User>users=new HashSet<User>();
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id==null?null:id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
} @ManyToMany(mappedBy="roles")
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
} }
package sys.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import sys.util.Constant;
@Table(name="a_user")
@Entity
public class User implements Serializable{
private Integer id; private String username;//用户名
private String password;//密码 private Set<Role>roles=new HashSet<Role>();
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id==null?null:id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
} @Column(length=64)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} @JoinTable(name="a_user_role",joinColumns={@JoinColumn(name="userId",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="roleId",referencedColumnName="id")})
@ManyToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE},fetch=FetchType.EAGER)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
} }
3、测试:
@Test
public void test6() {
// 1、级联保存
Set<Role>roles=new HashSet<Role>();
Set<User>users=new HashSet<User>();
Role role=roleService.getRole(1);
role.setUsers(users);
roles.add(role);
User user=new User();
//user.setId(-1);
user.setUsername("李彤");
user.setPassword("1144");
user.setRoles(roles);
users.add(user);
userService.save(user);
}
一测试就会出现以上错误!
4、解决方法。
解决的方法是设置一个Id值,任意设,如
user.setId(-1);
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: sys.entity.Role; nested exception is org.hibernate.PersistentObjectException: 的解决方案的更多相关文章
- jpa语句报 org.springframework.dao.InvalidDataAccessApiUsageException: Parameter with that position [2] did not exist; nested exception is java.lang.IllegalArgumentException: Parameter with that position
@Query("SELECT area from Area AS area WHERE area.state=0 AND area.name like %?1% ")Area fi ...
- org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
原因: 这个问题的解决方案很简单,主要是因为数据库中不存在相关的表或者列. org.springframework.dao.InvalidDataAccessApiUsageException: Pa ...
- Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Multiple representations of the same entity解决方法
1.错误信息 Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUs ...
- org.springframework.dao.InvalidDataAccessApiUsageException:The given object has a null identifi的解决方案
异常信息: org.springframework.dao.InvalidDataAccessApiUsageException: The given object has a null identi ...
- jpa遇到的 org.hibernate.PersistentObjectException: detached entity passed to persist异常
jpa遇到的 org.hibernate.PersistentObjectException: detached entity passed to persist异常 发生这个原因是因为我们已经在实体 ...
- javaEE-----org.springframework.dao.InvalidDataAccessApiUsageException: Write operation
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read ...
- org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [41] did not match expected type [java.lang.Integer (n/a)];
题记:以前记录过一些自己遇到的BUG,这个行为,让我一看报错的提示信息就能定位到问题的所在,后来记得比较多了,好多是重复性的再加上比较忙就没有详细的记录了,今天的工作量比较小,就顺便记录一下,以便以后 ...
- org.hibernate.PersistentObjectException: detached entity passed to persist异常
再用jpa+spring+struts2开发的是时候遇到一个问题(采用了注解的方式,xml配置的道理是一样的),当我在注册用户的时候,注册第一个用户没有问题,但注册第二个用户开始就会抛出一个异常: j ...
- org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode
[spring]:org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowe ...
随机推荐
- C# Windows Phone 8 WP8,切换各国语系免重开机 加速开发 送审有效率!!
原文:C# Windows Phone 8 WP8,切换各国语系免重开机 加速开发 送审有效率!! 一般我们在开发Windows Phone 8 时,会考虑到各国语言的问题,但是你有想过吗?用实体手机 ...
- 移动web:图片切换(焦点图)
在web页面上图片切换(焦点图)效果实在是太常见了,PC端.移动端到处都有它的身影. 上次写了个tab选项卡的效果,在这里延续一下,改成图片切换的效果. 如果不需要自动播放,稍微修改下html标签.和 ...
- 从原理角度解析Android (Java) http 文件上传
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/23781773 文件上传是我们项目中经常使用的功能,一般我们的服务器可能都是web ...
- 人人API 分享到人人功能 修改版
最近在搞一个日程管理网站, 需要实现分享到人人功能, 所以找了一下人人API, 然后根据自己需要修改了一下. 首先得有一个人人给的js文件, 如下: var Renren = Renren || {} ...
- php xss过滤
XSS已知CSS (Cross Site Script) ,跨站点脚本攻击.它指的是恶意攻击者Web插入恶意网页html代码,当用户浏览网页.其中嵌入Web里面html代码运行,从而实现了一些人的攻击 ...
- 【iOS】随机三角瓷砖布局算法
你已经看够iOS鉴于这些默认的正方形块,整齐地显示? 本篇给出一个随机算法设计的三角布局的瓷砖和实施. 这样的规则,并提出妥协随机排列间.它看起来很凌乱,不会有一个新事物. 重点是设计和实施,以实现布 ...
- JAVA Socket超时浅析(转)
套接字或插座(socket)是一种软件形式的抽象,用于表达两台机器间一个连接的“终端”.针对一个特定的连接,每台机器上都有一个“套接字”,可以想象它们之间有一条虚拟的“线缆”.JAVA有两个基于数据流 ...
- Codeforces Round #234 (Div. 2) B. Inna and New Matrix of Candies
B. Inna and New Matrix of Candies time limit per test 1 second memory limit per test 256 megabytes i ...
- Linux鸟哥的私房菜(3)— 总体规划和磁盘分区 读书笔记
1.每个硬件设备Linux中的文件名称 在Linux系统中.每一个设备都被当成一个文件来对待.而且差点儿全部的硬件设备文件都在/dev文件夹下 常见设备与其对于文件名称 2.磁盘连接的方式与设备文件名 ...
- RunJS推荐用于个人使用(使用方便JS、css实时预览、编辑、管理等功能)
RunJS,在线编写.展示html.js.css代码,拥有实时预览.分享.Fork.代码高亮.自己主动完毕等多项特性,提供文件上传.多种登录方式. 地址:http://runjs.cn/ waterm ...