I have an association mapped by the following:
@Entity
public class Parent
{
...
@Id
@Column(name = "parent_id")
private Long id;
@OneToMany(mappedBy = "parent")
@OrderBy("id")
private List<Child> children;
...
}
@Entity
public class Child
{
...
@Id
@Column(name = "child_id")
private Long id;
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "parent_id")
private Parent parent;
@Column
private Boolean enabled;
...
}
I would like to use the Criteria API to return a list of all of the Parent
entities which contain one or more Child
entities with the attribute enabled=false
. I would not like the mapped children
collection to be filtered by the query.
For example, given the following:
Parent A
- Child A enabled=true
- Child B enabled=false
Parent B
- Child A enabled=false
- Child B enabled=false
Parent C
- Child A enabled=true
- Child B enabled=true
The query should return the following:
Parent A
- Child A enabled=true
- Child B enabled=false
Parent B
- Child A enabled=false
- Child B enabled=false
So far I am using the following Criteria query:
Criteria crit = session.createCriteria(Parent.class);
crit.createCriteria("children").add(Restrictions.eq("enabled", false));
List<Parent> result = crit.list();
return result;
However it is returning the equivalent of
Parent A
- Child A enabled=true
- Child B enabled=false
Parent B
- Child A enabled=false
- Child B enabled=false
Parent B
- Child A enabled=false
- Child B enabled=false
Ie, it is returning a single parent record (with the children collection populated) for each child element with enabled=false
Does anyone know how to only return unique parent elements in this scenario?
Advice appreciated, p.
You need to add a distinct
, e.g.
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
should work in your case
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With