Donald
Donald

Reputation: 515

Hibernate Filters on related table with MappedSuperClass

I'm trying to filter to only show "Active" entities while making a query, using filters and a base MappedSuperClass and running into problems where the associated table classes aren't respecting the same filter.

Here's my model setup:

@FilterDef(name="baseStatus")
@Filter(name="baseStatus", condition= "Status = 'A'")
@MappedSuperclass
public abstract class BaseModel {

    @Column(name = "Status", insertable = false)
    private String status;

    // getters and setters...
}

I also have models that have related collections, eg..

@Entity
@Table(name = "A")
public class A extends BaseModel {
    @OneToMany()
    private List<B> bs = new ArrayList<B>(0);
// other model properties
}

@Entity
@Table(name = "B")
public class B extends BaseModel {
// model properties
}

Before querying, I run:

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(A.class)
Filter filter = getCurrentSession().enableFilter("baseStatus");
List<A> as = criteria.list();

Using this setup I get the proper filter applied to the main class I am querying, but the child collection ("bs") doesn't get filtered on the join, so I'm left with only active "A" with a child collection of "B", where some of the "B"s are inactive.

Ideally I'd like to only have the filter on the BaseModel. Is there any way to do what I'm looking for without applying a separate filter on each association?

Thanks!

Upvotes: 3

Views: 2163

Answers (1)

Donald
Donald

Reputation: 515

I couldn't find a great solution for this at the end without building something custom so I ended up annotating @Filter at each association table in each model as follows

@FilterDef(name="baseStatus")
@Filter(name="baseStatus", condition= "Status = 'A'")
@MappedSuperclass
public abstract class BaseModel {

    @Column(name = "Status", insertable = false)
    private String status;

    // getters and setters...
}

@Entity
@Table(name = "A")
public class A extends BaseModel {
    @OneToMany()
    @Filter(name="baseStatus", condition= "Status = 'A'")
    private List<B> bs = new ArrayList<B>(0);
// other model properties
}

@Entity
@Table(name = "B")
public class B extends BaseModel {
// model properties
}

While not ideal, it works and I still only need to call

Filter filter = getCurrentSession().enableFilter("baseStatus");

once in a common data access layer.

Upvotes: 3

Related Questions