krisy
krisy

Reputation: 1558

Filtering JPA eager fetched entites

I have a bunch of JPA entites (witch Hibernate) called Nodes, with the following fields:

The ParentNodeId refers to another Node, so I have a nice tree structure.

I've set the fetch type of Node to eager, so I get all the elements in the tree.

What I would like to do, is to filter the tree by Active property, that is get only those nodes, which has its Active field set to 1.

Is there an easy way to do this?

Thank, krisy

Upvotes: 1

Views: 804

Answers (1)

Wundwin Born
Wundwin Born

Reputation: 3475

You can use hibernate filter

  1. To define @FilterDef at entity class level

    @Entity
    @FilterDef (name="nodeFilter", 
                parameters = @ParamDef( name="activeParam", type="integer" ))
    
  2. Then define @Filter on desired property (at property level or at class level)

    @Filter(name = "nodeFilter", condition = "active = :activeParam") 
    
  3. Finally ENABLE the filter whenever/wherever you want (e.g findAllNodes() )

    Filter filter = session.enableFilter("nodeFilter");
    filter.setParameter("activeParam", 1);  //e.g Active is 1
    //then retrieve the result from session
    

More references : link1, link2, link3

Upvotes: 3

Related Questions