2

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?

Pedram Ezzati
  • 325
  • 3
  • 16
Anders
  • 181
  • 1
  • 1
  • 13

1 Answers1

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