5

使用过: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 passing to 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;

ETC...

道:

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
    }

ETC...

并根据表:

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

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

4

1 回答 1

12

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

检查您是否正在传递一个值以保留列 id,您已将其标记为:

@GeneratedValue(策略 = GenerationType.IDENTITY)

问候。

于 2014-03-19T14:25:40.327 回答