Search code examples
javamysqlhibernatehibernate-mapping

Hibernate criteria shows zero results but its generated query returns correct results


I am puzzled as I wrote following criteria that returns zero results however when I run its generated SQL query on my database returns correct results.

Criteria criteria = sessionFactory.getCurrentSession()
                .createCriteria(Product.class, "product")
                .add(Restrictions.ilike("product.name", " %" + name + "%"))
                .add(Restrictions.ilike("product.code", code))
                .setProjection(Projections.property("product.name").as("name"));

List<String> st = criteria.list();
System.err.println("st size is:" + st.size());


@Entity
public class Product implements java.io.Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 887867468898785287L;
    @Id
    private String code;
    @ManyToOne
    @Id
    private Factory factory;
    private String name;
    ...

}

Console output

Hibernate: 
    /* criteria query */ select
        this_.name as y0_ 
    from
        Product this_ 
    where
        lower(this_.name) like ? 
        and lower(this_.code) like ?
st size is:0

Solution

  • As Sergey Lagutin suggested, I suppose the issue would be the whitespace before % in your code. If that was not the solution check the Database connection to make sure you are connected to the correct database.