java - 如何使用 @ID 和 @GenerateValue 从 Hibernate + JPA 中的序列获取 Oracle 生成值

标签 java oracle hibernate jpa orm

我有以下 Oracle 表定义。

CREATE TABLE "SIAS"."OPERATION_REG"
  (
    "ID"               NUMBER CONSTRAINT "CT_OPERATION_REG_ID" NOT NULL ENABLE,
    "OPERATION_NAME"   VARCHAR2(30 BYTE),
    "APPLICATION_NAME" VARCHAR2(30 BYTE),
    "EXECUTION_DATE" DATE,
    "EXECUTION_USER" VARCHAR2(80 BYTE),
    "RESULT"         VARCHAR2(20 BYTE),
    CONSTRAINT "PK_OPERATION_REG_ID" PRIMARY KEY ("ID") USING INDEX PCTFREE 10 
     INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS NOLOGGING STORAGE(INITIAL 65536 NEXT 
     1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST 
     GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) 
     TABLESPACE "SIAS_DAT" ENABLE
  )
  SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 
  NOCOMPRESS LOGGING STORAGE
  (
    INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 
    0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT 
    CELL_FLASH_CACHE DEFAULT
  )
  TABLESPACE "SIAS_DAT" ;
CREATE UNIQUE INDEX "SIAS"."IDX_OPERATION_REG_ID" ON "SIAS"."OPERATION_REG"
  (
    "ID"
  )
  PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS NOLOGGING STORAGE
  (
    INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 
    FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT 
    CELL_FLASH_CACHE DEFAULT
  )
  TABLESPACE "SIAS_DAT" ;
CREATE OR REPLACE TRIGGER "SIAS"."BI_OPERATION_REG" BEFORE
  INSERT ON OPERATION_REG REFERENCING NEW AS NEW OLD AS OLD FOR EACH ROW BEGIN 
    :NEW.ID := SEQ_OPERATION_REG.NEXTVAL;
EXCEPTION
WHEN OTHERS THEN
  RAISE_APPLICATION_ERROR
  (
    -20255, 'ERROR EN TRIGGER BI_OPERATION_REG'
  )
  ;
END;
/
ALTER TRIGGER "SIAS"."BI_OPERATION_REG" ENABLE;

我启用了此触发器,以便在创建新行时自动生成 ID 列的值。

create or replace
TRIGGER BI_OPERATION_REG BEFORE INSERT
   ON OPERATION_REG
   REFERENCING NEW AS NEW OLD AS OLD
   FOR EACH ROW
BEGIN
   :NEW.ID           := SEQ_OPERATION_REG.NEXTVAL;
EXCEPTION
   WHEN OTHERS
   THEN
      RAISE_APPLICATION_ERROR (-20255, 'ERROR EN TRIGGER BI_OPERATION_REG');
END;

这是生成ID值的序列定义

CREATE SEQUENCE "SIAS"."SEQ_OPERATION_REG" MINVALUE 1 MAXVALUE 
999999999999999999999999999 INCREMENT BY 1 START WITH 37 NOCACHE NOORDER NOCYCLE ;

我无法控制数据库,因为 DBA 团队超出了我的范围,所以我必须处理这些定义。我创建了一个映射 OPERATION_REG 表的 JPA 实体。这是列 ID 的 ID 属性方法映射。

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "G1")
@SequenceGenerator(name = "G1", sequenceName = "SEQ_OPERATION_REG")
@Column(name = "ID")
public int getId() {
    return id;
}

这是我的实体映射的完整代码

    import org.hibernate.annotations.GenericGenerator;

    import javax.persistence.*;
    import java.sql.Timestamp;
    import java.util.Collection;

    @Entity
    @Table(name = "OPERATION_REG")
    public class OperationRegEntity extends BaseEntity {
        private int id;
        private String operationName;
        private String applicationName;
        private Timestamp executionDate;
        private String executionUser;
        private String result;
        private Collection<TokenRegEntity> tokenRegsById;
        private Collection<TraceRegEntity> traceRegsById;

        @Id
        @GeneratedValue(generator="select-generator")
        @GenericGenerator(name="select-generator", strategy="select", parameters = @org.hibernate.annotations.Parameter(name="key", value="ID"))
    //    @GeneratedValue(strategy = GenerationType.AUTO, generator = "G1")
    //    @SequenceGenerator(name = "G1", sequenceName = "SEQ_OPERATION_REG")
        @Column(name = "ID")
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Basic
        @Column(name = "OPERATION_NAME")
        public String getOperationName() {
            return operationName;
        }

        public void setOperationName(String operationName) {
            this.operationName = operationName;
        }

        @Basic
        @Column(name = "APPLICATION_NAME")
        public String getApplicationName() {
            return applicationName;
        }

        public void setApplicationName(String applicationName) {
            this.applicationName = applicationName;
        }

        @Basic
        @Column(name = "EXECUTION_DATE")
        public Timestamp getExecutionDate() {
            return executionDate;
        }

        public void setExecutionDate(Timestamp executionDate) {
            this.executionDate = executionDate;
        }

        @Basic
        @Column(name = "EXECUTION_USER")
        public String getExecutionUser() {
            return executionUser;
        }

        public void setExecutionUser(String executionUser) {
            this.executionUser = executionUser;
        }

        @Basic
        @Column(name = "RESULT")
        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            OperationRegEntity that = (OperationRegEntity) o;

            if (id != that.id) return false;
            if (applicationName != null ? !applicationName.equals(that.applicationName) : that.applicationName != null)
                return false;
            if (executionDate != null ? !executionDate.equals(that.executionDate) : that.executionDate != null)
                return false;
            if (executionUser != null ? !executionUser.equals(that.executionUser) : that.executionUser != null)
                return false;
            if (operationName != null ? !operationName.equals(that.operationName) : that.operationName != null)
                return false;
            if (result != null ? !result.equals(that.result) : that.result != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result1 = id;
            result1 = 31 * result1 + (operationName != null ? operationName.hashCode() : 0);
            result1 = 31 * result1 + (applicationName != null ? applicationName.hashCode() : 0);
            result1 = 31 * result1 + (executionDate != null ? executionDate.hashCode() : 0);
            result1 = 31 * result1 + (executionUser != null ? executionUser.hashCode() : 0);
            result1 = 31 * result1 + (result != null ? result.hashCode() : 0);
            return result1;
        }

        @OneToMany(mappedBy = "operationRegByOperationRegId")
        public Collection<TokenRegEntity> getTokenRegsById() {
            return tokenRegsById;
        }

        public void setTokenRegsById(Collection<TokenRegEntity> tokenRegsById) {
            this.tokenRegsById = tokenRegsById;
        }

        @OneToMany(mappedBy = "operationRegByOperationRegId")
        public Collection<TraceRegEntity> getTraceRegsById() {
            return traceRegsById;
        }

        public void setTraceRegsById(Collection<TraceRegEntity> traceRegsById) {
            this.traceRegsById = traceRegsById;
        }
    }

我有一个问题,因为当我创建一个新对象并将其保留在数据库中时,我遵循此策略

@Autowired
OperationRegService operationregservice;

@Transactional(propagation = Propagation.REQUIRES_NEW)
public OperationRegEntity createOperationReg(GenericRequestParameters parameters) {
    OperationRegEntity oper = new OperationRegEntity();
    oper.setApplicationName(parameters.getApplication());
    oper.setExecutionUser(parameters.getApplicationUser());
    oper.setOperationName(parameters.getSIASOperationName());
    oper.setExecutionDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
    oper.setResult("INITIATED");
    operationregservice.persist(oper);
    return oper;
}

当我分析oper.getID()的信息时,该值与数据库中创建的实际值不同,特别是总是低1点。例如,java 实体的 ID 值为 34,表行实体的 ID 值为 35,就好像序列被调用两次一样。有什么想法吗?

最佳答案

您不应该使用@SequenceGenerator,因为当您希望 Hibernate 在持久化实体时调用序列时,会使用它。

在您的用例中,数据库执行调用,因此您需要使用 select identifier generator strategy :

@Id
@GeneratedValue(generator="select-generator")
@GenericGenerator(name="select-generator", 
     strategy="select", 
     parameters = @org.hibernate.annotations.Parameter(name="key", value="ID")
)
@Column(name = "ID")
public int getId() {
    return id;
}

关于java - 如何使用 @ID 和 @GenerateValue 从 Hibernate + JPA 中的序列获取 Oracle 生成值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29772741/

相关文章:

sql - 使用 oracle 查询以平滑平均值填充表中缺失数据的间隙

java - hibernate @OneToMany错误: Duplicate entry '0' for key 'PRIMARY'

java - 解析模板时出错 [/],模板可能不存在,或者任何已配置的模板解析器都无法访问该模板

oracle - 在字符串前添加特定数量的零

java - 将 log4j JMSAppender 与 ActiveMQ 一起使用 - 调试级别中的有线格式超时(客户端)

oracle - 为什么即使禁用并行 DML 和并行 DDL 也会创建并行 session

HQL 的 Hibernate 拦截器/监听器

java - 在具有相同 PK 的 JPA/Hibernate OneToOne 双向关系中插入顺序错误

java - Android:手机 hibernate 时 Wi-Fi 强度不会改变

java - 具有大量列的 MySQL JPA 查询运行速度比预期慢得多