17

seu下面的映射

@Entity
public class User {

    private Integer id;

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

}

注意 id 是一个整数。现在我需要这个 HQL 查询,使用 like 运算符

Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.id like :userId");

ATT:它就像运算符 NOT =(等于运算符)

然后我用

List<User> userList = query.setParameter("userId", userId + "%").list();

但不起作用,因为 Hibernate 抱怨 IllegalArgumentException 发生调用 User.id 的 getter

即使我使用

query.setString("userId", userId + "%");

这没用

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

4

2 回答 2

30

根据休眠参考:

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

所以当我使用

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

它工作正常

于 2009-12-14T19:06:28.340 回答
7

好吧,LIKE 运算符通常用于文本数据,即 VARCHAR 或 CHAR 列,并且您有数字id列 (INTEGER)。

也许您可以尝试将id字段也映射为字符串并在查询中使用该字段。这可能会或可能不会工作,具体取决于您的数据库引擎。请注意,您应该通过处理所有更新setId()并将idAsString字段视为只读。

@实体
公共类用户{

    私人整数 id;
    私有字符串 idAsString;

    @ID;
    私人整数 getId() {
        返回这个.id;
    }

    私人无效setId(整数id){
        这个.id = id;
    }

    @Column(name="id", 可插入=false, 可更新=false)
    私人字符串 getIdAsString() {
       返回 this.idAsString;
    }

    私人无效 setIdAsString(字符串 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();
于 2009-12-14T18:56:39.060 回答