我有以下实体与枚举作为字段:
@Entity
@Table(name = "example")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Example implements Serializable {
@Id
@Column(name = "id")
private Integer id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type")
private Type type;
}
enum:
public enum Type implements Serializable {
EASY,
NORMAL,
HARD
}
最后,我有以下DTO:
public record ExampleDto(Integer id, String value) {
}
重要的是ExampleDto#value
具有String
类型而不是Type
类型。我想在Spring Data JPA
中使用DTO作为投影,但我遇到了一个问题。我不明白如何在JPQL查询中将枚举值转换为字符串。我试着这样做:
@Query("""
SELECT new com.example.project.ExampleDto(e.id, e.type.name)
FROM Example e
WHERE e.id = :id""")
ExampleDto findById(Integer id);
但它不起作用。如何在JPQL中将枚举转换为字符串?有可能吗?
1条答案
按热度按时间bmvo0sr51#
在构造ExampleDto时,JPA将自动将枚举值转换为字符串形式的名称。你不需要在枚举上显式调用name()。