分离的实体传递给持久化

时间:2012-04-16 04:01:46

标签: java spring hibernate entitymanager detach

使用:hibernate 3.6.10,maven 2,postgres 9。 我有必须工作的代码,但事实并非如此。 在我使用hibernate 3.6.2之前,我遇到了非常沮丧的错误: java.lang.ClassCastException:org.hibernate.action.DelayedPostInsertIdentifier无法强制转换为java.lang.Long

但是在更新到3.6.10之后错误变得更加明智: javax.persistence.PersistenceException:org.hibernate.PersistentObjectException:传递给persist的分离实体

代码是一个标准的域模型:

实体:

@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;

等...

DAO:

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

现在确定发布所有测试配置是个好主意,因为有很多解决方法。 有什么想法吗?

1 个答案:

答案 0 :(得分:3)

当您尝试在自动生成的列中保留值时,会引发此错误。

检查您是否传递了值以保留列ID,您将其列为:

  

@GeneratedValue(strategy = GenerationType.IDENTITY)

问候。