Search code examples
javahibernatejpaprojectionquerydsl

Hibernate ignore chained setter with projections beans


I am doing a simple query with QueryDsl / JPA / Hibernate which can be written like this:

SELECT u.id, u.name FROM user u WHERE u.id = 1;

I am using projections bean because of performance issue...

With QueryDsl the query look like this:

query.from(qUser).where(qUser.id.eq(1)).singleResult(
    Projections.bean(User.class,
        qUser.id,
        qUser.name
    )
);

My problem is in my User entity. I want to chain my setter so all setters return this. When I do that with projection bean Hibernate do not call setters (I saw it in debug mode.) so my User entity is not initialized.

For exemple with this User entity declaration:

@Entity(name = "USER")
public class User {

    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    public void setId(Long id) { //Setter called
        this.id = id;
    }

    public User setName(String name) { //Setter not called
        this.name = name;
        return this;
    }
}

I have a user returned by my query with null name:

User: {id: 1, name: null}

Is there a solution to solve this problem?


Solution

  • Actually after some researching and debugging deep inside Java Bean packages I figured out what was happening.

    Chaining setter is not Java Bean specification compliant. For that reason when QueryDsl do some introspection to initialize my bean, it call a getWriteMethod method that do not return "chaining setters"...

    So I think there is two options:

    First: Do not chain setter to respect Java Bean specs.

    Second: Instead of using QueryDsl Projections.bean() method use Projections.fields(). This last method will not use setters. So it can be good or not depending on your needs...