我有一个实体包含列枚举类型。
定义列枚举在实体中的类型如下:
@Column(name = "gender", columnDefinition = "number(3)", nullable = false)
@Enumerated(EnumType.ORDINAL)
private Gender gender;
我在下面创建了一个hql查询:
SELECT customer.nationalCode AS nationalCode,
customer.firstName AS firstName,
customer.lastName AS lastName,
customer.gender AS gender
FROM Customer customer
此查询返回枚举类型的性别 但我想获得性别序数而不是Enum Type 如何将列的枚举类型转换为整数?
答案 0 :(得分:0)
我尝试使用spring boot测试应用程序,它对我有用的唯一方法是在HQL中将枚举转换为int:
SELECT customer.nationalCode AS nationalCode,
customer.firstName AS firstName,
customer.lastName AS lastName,
CAST(customer.gender AS int) AS gender
FROM Customer customer
我使用的模型基于您的示例:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nationalCode;
private String firstName;
private String lastName;
@Column(name = "gender", columnDefinition = "number(3)", nullable = false)
@Enumerated(EnumType.ORDINAL)
private Gender gender;
//getters and setters
}
和枚举:
public enum Gender {
MALE, FEMALE;
}
编辑:这当然有效,如果你将enum作为ORDINAL保存在你的实体中(正如你现在所做的那样),否则你可能会得到一个NumberFormatException或类似的东西。