【问题标题】:Enum with method used in a query is not converted查询中使用的带有方法的枚举未转换
【发布时间】:2020-07-19 19:33:28
【问题描述】:

我使用带有 spring data jpa 的 spring boot

我有一个整数数据类型的字段。 我有一个该字段具有不同值的枚举

public class Operation{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "operation_Sequence")
    @SequenceGenerator(name = "operation_Sequence", sequenceName = "operation_Sequence", allocationSize = 1)
    private Long id;

    private Integer eventProcessStatus;
}

public enum EventProcessStatus {
    CLOSE(2),
    OPEN(99);

    private final int id;

    EventProcessStatus(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

在我的存储库中,我搜索将此枚举与 getId 方法一起使用

@Query(value = "select ce from Operation ce where "
            + "(ce.eventProcessStatus=com.ns.perma.domain.constants.EventProcessStatus.CLOSE.getId() )")
public List<Operation> findAllOperation();

执行此查询时,我得到 CLOSE: INVALID IDENTIFIER。

在我看到的sql日志中

...

where
operation0_.event_process_status=com.ns.perma.billing.domain.constants.EventProcessStatus.SUCCESS.getId() 

所以命令没有被转换。

有什么想法吗?

【问题讨论】:

  • 难道你不能通过自定义javax.persistence.AttributeConverterOperation 中的eventProcessStatus 类型更改为EventProcessStatus,如果你愿意的话,甚至可以简单地使用javax.persistence.Enumerated基于序数/字符串?
  • 你也可以添加Operation类吗?
  • 你的意思是不能修改类Operation?
  • 如果我使用转换器,需要如何修改查询

标签: java spring-boot jpa spring-data-jpa


【解决方案1】:

您不能在 JPQL 查询中使用任意 Java sn-ps。

但你可以使用SpEL expressions in a query annotation。 请注意,您需要使用special T operator to access static members。因此,以下(或类似的东西)应该可以工作:

@Query(value = "select ce from Operation ce where "
            + "ce.eventProcessStatus
= :#{ T(com.ns.perma.domain.constants.EventProcessStatus).CLOSE.id ")
public List<Operation> findAllOperation();

【讨论】:

  • 编译但在运行时失败
【解决方案2】:

@JensSchauder 是对的。你也可以试试这个方法。

您可以使用枚举值作为参数并传入查询

@Query(value = "select ce from Operation ce where ce.eventProcessStatus= ?1")
public List<Operation> findAllOperation(int enumValue);

然后使用枚举值调用这个函数

operationRepo.findAllOperation(EventProcessStatus.CLOSE.getId());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 2013-05-28
    • 2021-08-03
    • 2012-10-18
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多