T25
T25

Reputation: 15

Hibernate JoinTableFilter annotation

I'm using Hibernate to map my entities and I'm having a problem. I want my entity to retrieve a list of entity from another table, linked with a join table. I also want to filter on the join table to only retrieve objets whose boolean_value is set to false. It currently works without filtering, using @JoinTable annotation. I'm facing difficulties when it comes about @FilterJoinTable which seems not to be working.

Here is what I tried to do:

@Entity
@Table(name = "table_a")
@FilterDef(name="checkValue")
@Filter(name = "checkValue")
public class AEntity {
    // id ...

    @ManyToMany
    @JoinTable(name = "my_join_table",
            joinColumns = @JoinColumn(name = "a_id"),
            inverseJoinColumns = @JoinColumn(name = "b_id"))
    @FilterJoinTable(name = "checkValue", condition = "boolean_value = FALSE")
    private List<BEntity> objets;

}

Quick representation of my tables

Currently it returns all the objects from table_b without filtering.

Any idea of what I'm doing wrong ?

Upvotes: 0

Views: 573

Answers (2)

Phil Horder
Phil Horder

Reputation: 421

If your additional clause is static, then yes, a Where clause is the simplest fix.

If you want to vary the value, or turn the clause on & off on demand, then Filter is your solution.

However, you will then need to enable the filter and set parameters when you want to use it.

e.g.

@FilterDef(name="checkValue", 
  parameters = @ParamDef(name = "boolCheck", type = "boolean")
public class AEntity {
  // id ...

@ManyToMany
@JoinTable(name = "my_join_table",
        joinColumns = @JoinColumn(name = "a_id"),
        inverseJoinColumns = @JoinColumn(name = "b_id"))
@FilterJoinTable(name = "checkValue", condition = "boolean_value = :boolCheck")
private List<BEntity> objets;

and then enable the filter at the point of query:

Session session = entityManager.unwrap(Session.class);
session.enableFilter("checkValue").setParameter("boolCheck", false);
List<AEntity> results = aRepository.findAll();
...

session.disableFilter("checkValue");

Upvotes: 0

Christian Beikov
Christian Beikov

Reputation: 16430

You have to use the @Where annotation, as @FilterJoinTable allows defining Hibernate filters which have to be enabled explicitly with Session#enableFilter(String):

@ManyToMany
@JoinTable(name = "my_join_table",
        joinColumns = @JoinColumn(name = "a_id"),
        inverseJoinColumns = @JoinColumn(name = "b_id"))
@Where(clause = "boolean_value = FALSE")
private List<BEntity> objets;

Upvotes: 1

Related Questions