Hibernate JPA @Filter Example

@Filter

The @Filter annotation is used to add filters to an entity or the target entity of a collection.

Filter Add filters to an entity or a target entity of a collection.

@Filter
The @Filter annotation is another way to filter out entities or collections using custom SQL criteria. Unlike the @Where annotation, @Filter allows you to parameterize the filter clause at runtime.

Now, considering we have the following Account entity:

Example : @Filter mapping entity-level usage

@Entity(name = "Account")
@Table(name = "account")
@FilterDef(
    name="activeAccount",
    parameters = @ParamDef(
        name="active",
        type="boolean"
    )
)
@Filter(
    name="activeAccount",
    condition="active_status = :active"
)
public static class Account {

    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Client client;

    @Column(name = "account_type")
    @Enumerated(EnumType.STRING)
    private AccountType type;

    private Double amount;

    private Double rate;

    @Column(name = "active_status")
    private boolean active;

    //Getters and setters omitted for brevity
}
Notice that the active property is mapped to the active_status column.

This mapping was done to show you that the @Filter condition uses a SQL condition and not a JPQL filtering predicate.


@Filter mapping collection-level usage

@Entity(name = "Client")
@Table(name = "client")
public static class Client {

    @Id
    private Long id;

    private String name;

    private AccountType type;

    @OneToMany(
        mappedBy = "client",
        cascade = CascadeType.ALL
    )
    @Filter(
        name="activeAccount",
        condition="{a}.active_status = :active and {a}.type = {c}.type",
        aliases = {
                @SqlFragmentAlias( alias = "a", table= "account"),
                @SqlFragmentAlias( alias = "c", table= "client"),
        }
    )
    private List<Account> accounts = new ArrayList<>( );

    //Getters and setters omitted for brevity

    public void addAccount(Account account) {
        account.setClient( this );
        this.accounts.add( account );
    }
}

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation