是否可以在自定义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;
}
}
上面的代码运行良好,但是使用statusId
和getStatus
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;
}
请告诉我,这是可能的吗?
ORDINAL
从0
开始。它与用于表示 DB 中枚举的 ID (1
、2
、3
) 不兼容。 - davidxxx