Hibernate HQL query by using like operator

…衆ロ難τιáo~ 提交于 2019-12-18 18:53:50

问题


Seu the following mapping

@Entity
public class User {

    private Integer id;

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

}

Notice id is an Integer. Now i need this HQL query by using like operator

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

ATT: IT IS like operator NOT = (equals operator)

Then i use

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

But does not work because Hibernate complains IllegalArgumentException occured calling getter of User.id

Even when i use

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

It does not work

What should i use to pass the query ?


回答1:


According to Hibernate reference:

str() is used for converting numeric or temporal values to a readable string

So when i use

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

It works fine




回答2:


Well, LIKE operator is usually used with textual data i.e. with VARCHAR or CHAR columns, and you have numeric id column (INTEGER).

Maybe you could try to map id field also as string and use that field in query. This may or may not work depending on your database engine. Note that you should handle all updates via setId() and consider idAsString field to be read-only.

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

Then the query would be:

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


来源:https://stackoverflow.com/questions/1902686/hibernate-hql-query-by-using-like-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!