I have an entity with a collection of comments. Now I want to add a field "private" to it. Comments with private=true should not be included unless explicitly asked for. I can obviously just create a dto which filters the entities. Is it possible to add a filter on the model which can conditionally be turned on or off?
Asked
Active
Viewed 126 times
1 Answers
2
Yes, you can define a filter on the model:
@Entity
@Table(name="comments")
@FilterDef(name="commentFilter", parameters={
@ParamDef(name="private", type="boolean")
})
@Filters({
@Filter(name="commentFilter", condition=":private=isprivate")
})
public class Comments {
@Id
@Column(name="id")
private Integer id;
@Column(name="private")
private boolean private;
...
and for query
Session session = HibernateUtil.getSessionFactory().openSession();
System.out.println("--Enable Filter--");
Filter filter = session.enableFilter("commentFilter");
filter.setParameter("private",true);
session.beginTransaction();
List<Comments> results = session.createQuery("from Comments").list();

M-Razavi
- 3,327
- 2
- 34
- 46
-
Just make sure to replace the property name with a name that is not a reserved keyword. – senjin.hajrulahovic Oct 06 '18 at 19:03
-
@M-Razavi Thanks for your response. Would that still be possible if the main entity, say Post, contains an embedded collection of Comment? – Anders Oct 07 '18 at 11:22
-
@Anders yes, take look on this example: https://stackoverflow.com/a/42511037/601288 – M-Razavi Oct 07 '18 at 11:54