首页 > 解决方案 > 使用 querydsl 查询数字 varchars 并比较它们

问题描述

假设我有三个表,profile 和 profile_elements(一对多关联)和 element_type。

profile_elements 具有配置文件的所有元素以及 element_type_id 作为 element_type 表的外键,并具有列“value”,即 VARCHAR。

我想对 profile_elements 进行高级搜索。当我使用字符串时当然没有问题,但是例如,如果我想与“值”列的值进行比较(大于等),我不能,即使我知道,即当 element_id=1 时,这些值将是数字 varchars。我试图建立一个谓词

QprofileElements.profileElements.any().elementId.eq(1).and(QprofileElements.profileElements.any().value.castToNum(Long.class).gt(12345)

但是hibernate将其作为两个单独的select-from-where查询处理,并尝试将列的所有值强制转换为long,因此当它尝试转换包含字符的值时会发生错误。我什至设法使它如此休眠将其视为表单的一个查询

where element_id=1 AND cast(value)>12345

但它仍然有同样的问题。

有没有办法用 querydsl 或其他方法来克服这个问题?如果不是,有没有办法构造这个查询

select * 
from(
  (select * from profile_element pe where pe.element_id=1)
) as sq 
where cast(sq.value as int8)>12345 

用查询DSL?

我也尝试过 JPAExpressions,即使 when().then(),似乎也没有任何效果

版本

标签: javapostgresqlhibernatespring-data-jpaquerydsl

解决方案


您不需要嵌套的 SELECT,您可以简单地编写:

select * 
from profile_element pe 
where pe.element_id = 1
 and cast(pe.value as int8) > 12345;

使用 SQLQueryFactory 时,以下对我有用:

QprofileElements pe = new QprofileElements("pe");
queryfactory.
  select(pe.all()).
  from(pe).
  where(pe.attribId.eq(1).
    and(pe.attribValue.castToNum(Long.class).gt(1)));

推荐阅读