Hibernate 使用like运算符休眠HQL查询

Hibernate 使用like运算符休眠HQL查询,hibernate,hql,sql-like,Hibernate,Hql,Sql Like,Seu使用以下映射 @Entity public class User { private Integer id; @Id; private Integer getId() { return this.id; } } 注意,id是一个整数。现在,我需要使用like操作符来执行这个HQL查询 Query query = sessionFactory.getCurrentSession().createQuery("from User u wh

Seu使用以下映射

@Entity
public class User {

    private Integer id;

    @Id;
    private Integer getId() {
        return this.id;
    }

}
注意,id是一个整数。现在,我需要使用like操作符来执行这个HQL查询

Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.id like :userId");
ATT:它是运算符而不是=(等于运算符)

然后我用

List<User> userList = query.setParameter("userId", userId + "%").list();
它不起作用


我应该使用什么来传递查询?

嗯,LIKE运算符通常用于文本数据,即VARCHAR或CHAR列,并且您有numeric
id
列(整数)

也许您可以尝试将
id
字段也映射为字符串,并在查询中使用该字段。这可能有效,也可能无效,具体取决于数据库引擎。注意,您应该通过<代码> SETID()/代码>处理所有更新,并考虑<代码> IDASStase字段为只读。 @Entity public class User { private Integer id; private String idAsString; @Id; private Integer getId() { return this.id; } private void setId(Integer id) { this.id = id; } @Column(name="id", insertable=false, updatable=false) private String getIdAsString() { return this.idAsString; } private void setIdAsString(String idAsString) { this.idAsString = idAsString; } } @实体 公共类用户{ 私有整数id; 私有字符串idAsString; @身份证; 私有整数getId(){ 返回此.id; } 私有void setId(整数id){ this.id=id; } @列(name=“id”,insertable=false,updateable=false) 私有字符串getIDassString(){ 返回此.idAsString; } 私有void集合idAsString(字符串idAsString){ this.idAsString=idAsString; } } 那么查询将是:

Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.idAsString like :userId");
List<User> userList = query.setParameter("userId", userId + "%").list();
Query Query=sessionFactory.getCurrentSession().createQuery(“来自用户u,其中u.idAsString类似:userId”);
List userList=query.setParameter(“userId”,userId+“%”)。List();

根据Hibernate参考:

str()用于将数值或时间值转换为可读字符串

所以当我使用

from User u where str(u.id) like :userId

它工作得很好

你使用的是什么数据库引擎?@Arthur-没有回答你的问题(看来你自己已经弄明白了),但我只想问一下-为什么?我真的很感兴趣-您有什么样的用例需要对似乎是代理键的内容进行类似的比较?@chsply76-Hi-Chss。这是一个遗留系统。这是一种树状结构,其中父组id匹配所有子组id。例如,如果我有一个组id=22100,并且我想检索其子组id,通过匹配221前缀,我使用>>>如“221%”。亚瑟-我明白了。考虑到基础列是数字的(并且,作为PK,很可能是索引的),进行数字比较可能会获得更好的性能。例如,对于上面的示例,您需要执行
其中userId>22100和userId<22200
。根据您的数据库引擎和表大小,差异可能非常大(因为这里将使用索引,但不会用于LIKE)@ChssPly76谢谢您的回复。这真是个好主意。在这种情况下,我想我需要使用正则表达式来检索它的前缀。但是有一些限制,因为在某些情况下,我需要检索一些孩子,而不是全部。因此,您的解决方案可能无法按预期工作。是的。str()给了我答案。我也遇到了同样的问题,因为我的实体类有很长的字段。我使用了类似Hibernate的操作符,它给了我强制转换异常。通过hibernate str()方法找到了解决方案,我使用了hibernate查询。请查找示例查询。从Bill b中选择b.billNumber,其中str(b.billNumber)类似于:billNumber”).setString(“billNumber,您的_参数).list();
from User u where str(u.id) like :userId