JPA实体中的枚举类型字段

Boh*_*nko 2 java jpa spring-data-jpa

可以在自定义JPA实体中将枚举用作字段(列)的类型吗?这是一个例子:

@Getter @Setter
@Entity
@Table(name = "payments")
public class PaymentEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "status")
    private Integer statusId;

    public PaymentStatuses getStatus() {
        return PaymentStatuses.valueOf(statusId);
    }

    public PaymentEntity setStatus(PaymentStatuses status) {
        statusId = status == null ? null : status.getId();
        return this;
    }
}

public enum PaymentStatuses {
    CREATED(1),
    COMPLETED(2),
    CANCELED(3);


    private Integer id;

    private PaymentStatuses(Integer id) {
        this.id = id;
    }

    public Integer getId() {
         return id;
    }

    public static PaymentStatuses valueOf(Integer id) {
        for (PaymentStatuses value : values())
            if (value.getId().equals(id))
                return value;
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,但用的方法statusIdgetStatus setStatus长相丑陋一点点。

我想PaymentStatuses用作实体中的字段类型。像这样:

@Getter @Setter
@Entity
@Table(name = "payments")
public class PaymentEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "status")
    private PaymentStatuses status;
}
Run Code Online (Sandbox Code Playgroud)

请告诉我,有可能吗?

dav*_*xxx 5

@Enumerated(EnumType.ORDINAL)由于该ORDINAL模式开始,因此无法使用0
所以枚举的3个第一值将在DB与来表示012的值。
id枚举中表示它在数据库中的字段从1移至3

CREATED(1),
COMPLETED(2),
CANCELED(3);
Run Code Online (Sandbox Code Playgroud)

此外,这种方式可以将枚举中定义的元素顺序与在数据库中表示元素的方式相关联。将来可以添加/删除枚举值,这不是一件好事。

解决您的问题的更好方法是定义javax.persistence.AttributeConverter和一起使用@Convert
因此,创建一个AttributeConverter实现以指示如何从数据库转换为枚举以及将枚举转换为数据库。
然后PaymentStatuses status在您的实体中声明一个,并@Convert通过指定AttributeConverter实现类对其进行注释。

@Getter @Setter
@Entity
@Table(name = "payments")
public class PaymentEntity {
  ...
  @Convert(converter = PaymentStatusesConverter.class)
  private PaymentStatuses status;
  ...    
}

public class PaymentStatusesConverter  implements AttributeConverter<PaymentStatuses, Integer> {

    @Override
    public Integer convertToDatabaseColumn(PaymentStatuses status) {
        return status.getId();
    }

    @Override
    public PaymentStatuses convertToEntityAttribute(Integer status) {
         return PaymentStatuses.valueOf(status); 
    }
}
Run Code Online (Sandbox Code Playgroud)