Excluding bean field in hibernate results

This is how I get my User beans from the database.

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

      

This returns all user records from the database. The interesting part is that I don't want to get the password field from the DB. I just want to exclude this field when fetching.

I have

1) using projections in other fields. It should be more code to add to the forecast list. Thus, he abandoned this idea.

2) With Sql, I need to write a query by hand that kills the Hibernate theme.

Any opportunity to exclude the value of the Bean column?

+4


source to share


2 answers


Suppose the following is your POJO:

User.java

private long id;
private String fName;
private String lName;

// getter - setter of all fields

      

Now, suppose you only want to get the id

and fields fName

, not lName

.

Apart from the two approaches you described, there is also a third way to achieve this, which is using HQL.



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

      

Modify User.java to have the following constructor like this:

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

      

In short, whatever fields you want, you can list them both in the constructor and in the query.

Hope it helps.

+5


source


you may 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();

      



Link : -

+8


source







All Articles