[英]detached entity passed to persist
使用:hibernate 3.6.10,maven 2,postgres 9。我有必须工作的代码,但它没有。 在我使用 hibernate 3.6.2 并得到非常沮丧的错误之前:java.lang.ClassCastException: org.hibernate.action.DelayedPostInsertIdentifier cannot be cast to java.lang.Long
但是在更新到 3.6.10 之后错误变得更明智了:javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity传递给持久化
代码是一个标准的领域模型:
实体:
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@Entity
@Table(schema = "simulators", name = "mySimulator_card")
public class MySimulatorCard {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "account_number", unique = true, nullable = false)
private String accountNumber;
等等...
道:
public abstract class AbstractDao<E, PK extends Serializable> implements Dao<E, PK> {
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
@PersistenceContext(unitName = "MySimulator")
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public abstract Class<E> getEntityClass();
@Override
public void persist(E e) {
getEntityManager().persist(e);//<-- some thing wroooong
}
等等...
并根据表:
CREATE TABLE simulators.mySimulator_card
(
id bigserial NOT NULL,
account_number character varying(255) NOT NULL,
etc...
CONSTRAINT mySimulator_card_pk PRIMARY KEY (id),
CONSTRAINT mySimulator_card_account_fk FOREIGN KEY (account_id)
REFERENCES simulators.mySimulator_account (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT mySimulator_card_currency_fk FOREIGN KEY (currency_id)
REFERENCES simulators.mySimulator_currency ("name") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT mySimulator_card_product_fk FOREIGN KEY (product_id)
REFERENCES simulators.mySimulator_product (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT mySimulator_account_account_number_uq UNIQUE (account_number),
CONSTRAINT mySimulator_card_san_uq UNIQUE (san)
)
WITH (
OIDS=FALSE
);
ALTER TABLE simulators.mySimulator_card OWNER TO functional;
我认为功能测试中的上下文有问题,因为生产工作正常。 此外,当我尝试使用此技巧从 entityManager 获取会话时:
EntityManager em = getEntityManager();
HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
Session session = hem.getSession();
session.persist(e);
我有错误:
java.lang.IllegalStateException: 没有可用的事务 EntityManager
现在确定发布所有测试配置是个好主意,因为有很多解决方法。 任何的想法?
当您尝试在自动生成的列中保留值时,会引发此错误。
检查您是否正在传递一个值来持久化列 id,您已将其标记为:
@GeneratedValue(策略 = GenerationType.IDENTITY)
问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.