使用sql序列生成的id不一致

时间:2014-03-12 09:08:25

标签: java sql oracle hibernate

我有一个Trace类,我需要将它的实例保存在Oracle DB中。

我选择使用序列生成其id,如下所示:

@Entity
@Table(name = "TRACES")
@SequenceGenerator(name = "TraceGen", sequenceName = "SEQ_TRACE_ID")
public class Trace {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TraceGen")
    @Column(name = "TRACE_ID")
    int traceId;
    @Column(name = "DEAL_ID")
    String dealId;
    // etc.

    public Trace(int traceId, String dealId, String nttId, Long runId, String step, String type, String trace, Date date) {
        super();
        this.traceId = traceId;
        this.dealId = dealId;
        this.nttId = nttId;
        this.runId = runId;
        this.step = step;
        this.type = type;
        this.trace = trace;
        this.date = date;
    }
}

代码中的其他地方,我创建了我的Trace实例并将其保存为:

traceDAO.setTrace(new Trace(0, deal.getId(), ntt.getId(), run.getRunId(), "AAA", type, message, new Date()));

TraceDao类:

@Repository("traceDAO")
@Transactional("cvaTxManager")
public class TraceDAO implements TraceAccess {

    @Autowired
    @Qualifier("cvaSessionFactory")
    private SessionFactory sessionFactory;
    private Session session;

    @Override
    public void setTrace(Trace trace) throws HibernateException {
        if (session == null) {
            session = sessionFactory.openSession();
        }
        session.beginTransaction();
        session.save(trace);
        session.getTransaction().commit();
    }
}

序列创建于:

CREATE SEQUENCE SEQ_TRACE_ID MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 NOCACHE NOORDER NOCYCLE ;

问题:

select SEQ_TRACE_ID.nextval from dual返回1035

但是,当我想在TRACES表中使用insert into TRACES (TRACE_ID, RUN_ID, NTT_ID, DEAL_ID, STEP, TYPE, TRACE, DATE_INSERT) VALUES (seq_acc_trace_id.nextval, 22, '', '', '', '', '', '')手动插入新行时,我收到此错误:

SQL Error: ORA-00001: unique constraint (PRD.PK_TRACE_ID) violated 00001. 00000 - "unique constraint (%s.%s) violated" *Cause: An UPDATE or INSERT statement attempted to insert a duplicate key. For Trusted Oracle configured in DBMS MAC mode, you may see this message if a duplicate entry exists at a different level. *Action: Either remove the unique restriction or do not insert the key.

我该怎么办?

另外,在TRACES表格中,我有id > SEQ_TRACE_ID.nextval的痕迹是正常的吗?

1 个答案:

答案 0 :(得分:0)