在Spring Boot中使用合成ID自动生成ID

时间:2020-08-27 06:13:16

标签: spring-boot

我想向实体类添加自动生成ID

这是我的实体课程

    @Entity
    @Getter
    @Setter
    @NoArgsConstructor
    @Audited
    @IdClass(TranKey.class)
    
 public class Tran{
    
        @Id
        @NotNull
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
    
        @Id
        @NotNull
        @Enumerated(EnumType.STRING)
        private TranSourceEnum tranSource;
    
        @Id
        @NotNull
        @Column(unique = true)
        private String tranId;
    
        private String responseCode;
    
        private String failureReason;
    
        @NotNull
        private Date tranCreSysDate;
    
        private String switchingId;

    }

这是复合键类

    @Getter
    @Setter
    @Embeddable
    public class TransKey implements Serializable {
    
        @Column(name = "tranSource")
        @Enumerated(EnumType.STRING)
        TranSourceEnum tranSource;
    
        @Column(name = "tranId")
        String tranId;
    
        public TransKey(){}
    
        public TransactionKey(TranSourceEnum tranSource, String tranId){
            super();
            this.tranId = tranId;
            this.tranSource = tranSource;
        }
    }

我想像上面的实体类一样添加自动生成的id字段...但这是行不通的.... 不是自动生成。...有可能使用复合键添加另一个id字段。

如果可能的话,正确的方法是什么

谢谢

1 个答案:

答案 0 :(得分:0)

尝试一下:

   @IdClass(TranKey.class)
public class Tran{
    
    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Id
    @NotNull
    @Enumerated(EnumType.STRING)
    private TranSourceEnum tranSource;

    @Id
    @NotNull
    @Column(unique = true)
    private String tranId;

    private String responseCode;

    private String failureReason;

    @NotNull
    private Date tranCreSysDate;

    private String switchingId;

}

这样编写密钥类:

@Getter @Setter

public class TransKey implements Serializable {
    
    private TranSourceEnum tranSource;
    private String tranId;
    private Integer id;
    }