使用like运算符进行Hibernate HQL查询

Art*_*ald 16 hibernate hql sql-like

Seu以下映射

@Entity
public class User {

    private Integer id;

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

}
Run Code Online (Sandbox Code Playgroud)

注意id是一个Integer.现在我需要使用like运算符来进行这个HQL查询

Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.id like :userId");
Run Code Online (Sandbox Code Playgroud)

ATT:它就像运营商NOT =(等于运营商)

然后我用

List<User> userList = query.setParameter("userId", userId + "%").list();
Run Code Online (Sandbox Code Playgroud)

但是没有用,因为Hibernate抱怨IllegalArgumentException发生了调用User.id的getter

即使我使用

query.setString("userId", userId + "%");
Run Code Online (Sandbox Code Playgroud)

这是行不通的

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

Art*_*ald 29

根据Hibernate参考:

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

所以当我使用

from User u where str(u.id) like :userId
Run Code Online (Sandbox Code Playgroud)

它工作正常


Juh*_*älä 7

那么,LIKE运算符通常与文本数据一起使用,即使用VARCHAR或CHAR列,并且您有数字id列(INTEGER).

也许您可以尝试将id字段映射为字符串并在查询中使用该字段.根据您的数据库引擎,这可能有效,也可能无效.请注意,您应该通过setId()并处理所有更新,并将idAsString字段视为只读.

@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;
    }
}

那么查询将是:

Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.idAsString like :userId");
List<User> userList = query.setParameter("userId", userId + "%").list();
Run Code Online (Sandbox Code Playgroud)