hibernate 如何在JPQL查询中获取枚举的值?

m3eecexj  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(81)

我有以下实体与枚举作为字段:

@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中将枚举转换为字符串?有可能吗?

bmvo0sr5

bmvo0sr51#

在构造ExampleDto时,JPA将自动将枚举值转换为字符串形式的名称。你不需要在枚举上显式调用name()。

@Query("""
       SELECT new com.example.project.ExampleDto(e.id, e.type)
       FROM   Example e 
       WHERE  e.id = :id""")
ExampleDto findById(Integer id);

相关问题