首页 > 解决方案 > 自动增量版本字段作为复合键的一部分

问题描述

我有一个具有复合主键的表

CREATE TABLE workflow_metadata
(
  -- other fields here
  version NUMBER(10) NOT NULL,
  workflow_key VARCHAR2(255) NOT NULL,
  CONSTRAINT pk_wf_metadata PRIMARY KEY (version, workflow_key)
);

以及用于自动递增版本字段的序列。

CREATE SEQUENCE workflow_version_seq INCREMENT BY 1 START WITH 1;

这是该实体类的 Java 代码。我正在使用 Spring Data Rest 的存储库来持久化/检索此类实体。

@Data
@Entity
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@SequenceGenerator(name = "workflow_version_seq", allocationSize = 1)
@IdClass(WorkflowMetadataId.class)
public class WorkflowMetadata implements Persistable<WorkflowMetadataId> {
    @Id
    private String workflowKey;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "workflow_version_seq")
    private Integer version;

    // ------
    // Other fields were omitted to keep this sample rather small.
    // ------

    // This last part is added for altering the default behaviour of Spring Data Rest, which is updating an entity with same primary key rather than failing when trying to insert it in the DB.
    // https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-persistence.saving-entites.strategies
    // This is just a flag used for holding the new state.
    // This field will not be persisted in the DB.
    @Transient
    private boolean isNew = true;

    @Transient
    private WorkflowMetadataId workflowMetadataId = null;

    @Override
    public WorkflowMetadataId getId() {
        return new WorkflowMetadataId(workflowKey, version);
    }

    @Override
    public boolean isNew() {
        return isNew;
    }

    @PrePersist
    @PostLoad
    void markNotNew() {
        this.isNew = false;
    }
}


// this is in a separate file
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WorkflowMetadataId implements Serializable {
    private String workflowKey;
    private Integer version;

}

version每次workflowKey尝试持久化具有相同的新实体时,我都试图让该字段自动递增。

但是,到目前为止,我所做的保证了version每个表都有一个唯一的字段。但我只希望version每个共享相同的实体都有一个唯一字段workflowKey。这是可以实现的吗?请指出我正确的方向。

一些例子。

在以下 3 次插入之后:

INSERT INTO table workflow_metadata (workflow_key) VALUES ('wf01');
INSERT INTO table workflow_metadata (workflow_key) VALUES ('wf01');
INSERT INTO table workflow_metadata (workflow_key) VALUES ('wf02');

我在数据库中有什么:

(workflowKey, version)
wf01, 1
wf01, 2
wf02, 3

我在数据库中想要什么:

(workflowKey, version)
wf01, 1
wf01, 2
wf02, 1

标签: springoraclehibernatespring-data-restcomposite-primary-key

解决方案


推荐阅读