Search code examples
javahibernatehql

How to get not full collection using Hibernate?


I study Hibernate and now have such structure:

Class Person:

@Entity
public class Person {

  ...

  @OneToMany(...)
  private List<Task> tasks;

  ...

}

Class Task:

@Entity
public class Task {

  ...

  @Column(...)
  private boolean isCompleted;

  @ManyToOne(...)
  private Person person;

  ...

}

My question is: How can I get Person object with only tasks which are completed? I tried this HQL query using Hibernate Session:

SELECT person FROM Person person JOIN Task task WIH task.completed = true

but of course I get just persons that have completed tasks but every list cotains the rest of them also. I've heard something about Criteria abilities but it's deprecated. So how can I do it via HQL or some new API? I use Hibernate 5. Thanks for any help.


Solution

  • Try this

    @OneToMany(...) @Where(clause = "is_completed = true")

    Please note that you have to write sql in the @Where clause value, since this will be applied during native sql generation.

    From documentation-

    • Where clause to add to the element Entity or target entity of a collection
    • The clause is written in SQL