实体主键和序列

时间:2015-03-19 13:27:58

标签: oracle primary-key

我使用oracle和openjpa。 我有一个主键,我想使用序列作为其值

CREATE TABLE LOG (
    ID  NUMBER(10)          not null,
    TIMESTAMP               TIMESTAMP DEFAULT (SYSDATE),
    constraint PK_ID  PRIMARY KEY (ID)
);

CREATE SEQUENCE ID_SEQ
 START WITH     1
 INCREMENT BY   1
 NOCACHE
 NOCYCLE;


@Entity
@Table(name="Log")
public class Log implements Serializable  {
    @Id
    @SequenceGenerator(name="SEQ_GEN", sequenceName="ID_SEQ", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_GEN" )
    @Column(name="id",nullable=false)
    private long id;

    @Column(name="timestamp",nullable=false)
    private Timestamp timestamp;

    public Log(){
    }

    public Log(Timestamp timestamp){
        this.timestamp = timestamp;
    }
    ..
}

@Stateless
public class LogDAO {

    @PersistenceContext(unitName="logEntityPU")
    private EntityManager em ;


    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public boolean insert(Log log){
      em.persist(log);
      return true;
    }
    ...
    ...
}

当我检查我的Log对象时,id = 0且时间戳正常

但是我收到了这个错误 ORA-01400:完整性约束违规:NOT NULL检查约束。不允许插入空值

就像jpa不与序列链接。

当我调试更多时,我看到这个错误:javax.persistence.TransactionRequiredException:PuId没有活动事务=

任何想法?

1 个答案:

答案 0 :(得分:0)

这样的触发器将插入主键(如果应用程序未提供主键

CREATE OR REPLACE TRIGGER YOUR_SCHEMA.TRG_YOUR_TABLE
BEFORE INSERT 
ON YOUR_SCHEMA.YOUR_TABLE
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
DECLARE
   PrimaryKeyId NUMBER;

BEGIN
      IF :NEW.PRIMARY_KEY_ID IS NULL THEN
         SELECT your_schema.seq_your_table.nextval
         INTO :NEW.PRIMARY_KEY_ID
         FROM dual;
      END IF;

END YOUR_SCHEMA.TRG_YOUR_TABLE;

然后做一个

Select YOUR_SCHEMA.seq_your_table.currval from dual;

获取值