带整数的JPA Like运算符

yfjy0ee7  于 2023-01-21  发布在  其他
关注(0)|答案(5)|浏览(152)

谁能告诉我,为什么这是行不通的:

criteria.add(cb.like((myentity.<Integer>get("integerid")).as(String.class), "2%"))

出现以下错误:

The object [2%], of class [class java.lang.String], from mapping [org.eclipse.persistence.mappings.DirectToFieldMapping[integerid-->MYENTITY.INTEGERID]] with descriptor [RelationalDescriptor(org.example.model.MyEntity --> [DatabaseTable(MYENTITY)])], could not be converted to [class java.lang.Integer]

为了使用like运算符,唯一的解决方案是在模型中将myinteger属性更改为字符串吗?
BR

o7jaxewo

o7jaxewo1#

下面是它如何与JPA一起工作的例子,所以你可以在你的JPQL中使用带有整数的LIKE。

public List<MyEntity> getMyEntities(String idStr) {
   return entityManager.createQuery("SELECT m FROM MyEntity m WHERE CAST( m.id AS string ) LIKE :idStr")
         .setParameter("idStr", "%" + idStr+ "%").getResultList();
}

注意:我测试了它,工作正常,我正在使用JPA 2.1与Hibernate提供程序。

col17t5w

col17t5w2#

JPA不支持带有整数的like(),只支持字符串。有些数据库支持带有整数的like,有些则不支持。
EclipseLink应该允许在Integer中使用like()(只要你的数据库支持)。你使用的是什么版本?可能需要使用〉= 2.1。如果在最新版本中失败,请记录bug。
您还可以根据数据库使用“CHAR”、“TO_CHAR”或“CONVERT”函数将整数转换为字符串。条件API支持function()API调用本机函数。
注意,as()API不是用于从Integer转换为String,而是用于强制转换为子类实体。

i2loujxw

i2loujxw3#

我的猜测是:你试图把一个字符串放在integerId中,而integerId是一个整数。
此外,对整数值的类似是不可能的。
将String.class更改为Integer.class,并将“2%”更改为整数值

qhhrdooz

qhhrdooz4#

我也遇到过同样的问题,我使用JPA2.0和EclipseLink 2.3作为实现。
codeClient 实际上是我的数据库中的一个Integer。
注解@Convert只是将Integer列转换为String列。
这样我就可以用一个like predicate 来表示数字。

@Entity
@Table(name="COLIS_SO_VM")
public class Colis implements Serializable {

    ...

    @Convert
    private String codeClient;

    ...
}

我知道这是一个老职位,但如果它可以帮助别人!

mwyxok5s

mwyxok5s5#

可以通过将整数转换为字符串,然后使用类似匹配来实现。
以下查询对整数receiverUserId与数字子字符串匹配的记录进行计数:

@Query("select count(s.id) from SupportCouponInfo s where cast(s.receiverUserId as string) like concat('%',:numericSubstring,'%')")
fun countByReceiverUserIdContaining(numericSubstring: String): Long

相关问题