Excluding a bean's field in Hibernate criteria result

前端 未结 2 1164
梦谈多话
梦谈多话 2020-12-29 18:01

Here is how I\'m getting my User beans from Database.

session.createCriteria(User.class).list();

That returns all of User records from data

相关标签:
2条回答
  • 2020-12-29 18:18

    you can try:

    Example example = Example.create(cat)
        .excludeZeroes()           //exclude zero valued properties
        .excludeProperty("color")  //exclude the property named "color"
        .ignoreCase()              //perform case insensitive string comparisons
        .enableLike();             //use like for string comparisons
    List results = session.createCriteria(Cat.class)
        .add(example)
        .list();
    

    Reference :-

    • http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/querycriteria.html#querycriteria-examples
    • http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/criterion/Example.html
    0 讨论(0)
  • 2020-12-29 18:21

    Let's assume that following is your POJO:

    User.java

    private long id;
    private String fName;
    private String lName;
    
    // getter - setter of all fields
    

    Now suppose you want to get only id & fName fields and not lName.

    Apart from the two approaches you've described, there's also a third way to achieve this, which uses HQL.

    Query q1 = session.createQuery("Select new User(id, fName) from User");
    List<User> users = q1.list();
    

    Modify User.java to have another constructor as follows:

    public User(long id, String fName)
        {
            this.id = id;
            this.fName = fName;
        }
    

    In short, whatever fields you want to retrieve, you can list them in the constructor as well as in the query.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题