【JPA】JPA 多对多映射报错信息:detached entity passed to persist原因汇总
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.wxl.pojo.Tag; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.wxl.pojo.Tag
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:299)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
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:133)
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.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(Surroun
原因一:
保存时预先设置一个任意主键:
blog.setId((long) 0);
原因二
比如:在实体类中定义的变量如下:
@Id
@GeneratedValue
private Long id;//主键
系统默认这个值是由数据库自动生成的,可是你的数据库并没设置其为identity属性.
这样就会报错.
解决办法1.在存储数据的时候,要记得把id这一项设置为空.否则,是不可以存储的,因为已经identity了.
解决办法2.去掉 @GeneratedValue()
原因三
将 @ManyToMany 的 cascade 属性设置为 Cascade.MERGE 或者 Cascade.REFRESH ,慎用 Cascade.ALL