代码之家  ›  专栏  ›  技术社区  ›  Arthur Ronald

使用like运算符休眠HQL查询

  •  15
  • Arthur Ronald  · 技术社区  · 16 年前

    Seu使用以下映射

    @Entity
    public class User {
    
        private Integer id;
    
        @Id;
        private Integer getId() {
            return this.id;
        }
    
    }
    

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

    ATT:是的 喜欢 操作员不 =

    然后我用

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

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

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

    它不起作用

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

    2 回复  |  直到 16 年前
        1
  •  30
  •   Arthur Ronald    16 年前

    根据Hibernate参考:

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

    所以当我使用

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

        2
  •  7
  •   Juha Syrjälä    16 年前

    好的,LIKE运算符通常用于文本数据,即VARCHAR或CHAR列,并且您有数字 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();