SpringDataJPA中出现的保存出现的Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist:
出现这种问题是先看看自己的实体类主键策略
通常原因分两种:
1.@GeneratedValue(strategy=GenerationType.IDENTITY)
这种主键策略是自增长,数据库中设置主键自增和在对应的实体类中设置对应的主键自增,只要有哪一边没有设置,就会报该异常
2.我的数据表主键不是自增长,如图
这是我自己写的主键生成策略
*主键生成工具类
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class PrimaryKeyAlgorithmUtil {
private static final long ONE_STEP = 10;
private static final Lock LOCK = new ReentrantLock();
private static long lastTime = System.currentTimeMillis();
private static short lastCount = 0;
private static int count = 0;
@SuppressWarnings("finally")
public static Long nextId()
{
LOCK.lock();
try {
if (lastCount == ONE_STEP) {
boolean done = false;
while (!done) {
long now = System.currentTimeMillis();
if (now == lastTime) {
try {
Thread.currentThread();
Thread.sleep(1);
} catch (java.lang.InterruptedException e) {
}
continue;
} else {
lastTime = now;
lastCount = 0;
done = true;
}
}
}
count = lastCount++;
}
finally
{
LOCK.unlock();
return Long.parseLong(lastTime+""+String.format("%03d",count));
}
}
}
*主键生成器
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import java.io.Serializable;
public class PrimaryKeyGenerator extends IdentityGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws MappingException {
Object id = PrimaryKeyAlgorithmUtil.nextId();
if (id != null) {
return (Serializable) id;
}
return super.generate(session, object);
}
*实体类
上图权限类和用户类为多对多的对应关系 现要插入一个,用户有多个权限
当项目启动后调这个方法会出现异常
这是因为数据表主键没有设置自增长,实体类也没设置id数据无法保存
只需要给实体setId(id)即可解决。