2020-08-21

Hibernate JPA @SqlFragmentAlias Example

@SqlFragmentAlias

The @SqlFragmentAlias annotation is used to specify an alias for a Hibernate @Filter.

The alias (e.g. myAlias) can then be used in the @Filter condition clause using the {alias} (e.g. {myAlias}) placeholder.

@Filter with @SqlFragmentAlias
When using the @Filter annotation and working with entities that are mapped onto multiple database tables, you will need to use the @SqlFragmentAlias annotation if the @Filter defines a condition that uses predicates across multiple tables.

Example :@SqlFragmentAlias mapping usage

@Entity(name = "Account")
@Table(name = "account")
@SecondaryTable(
name = "account_details"
)
@SQLDelete(
sql = "UPDATE account_details SET deleted = true WHERE id = ? "
)
@FilterDef(
name="activeAccount",
parameters = @ParamDef(
name="active",
type="boolean"
)
)
@Filter(
name="activeAccount",
condition="{a}.active = :active and {ad}.deleted = false",
aliases = {
@SqlFragmentAlias( alias = "a", table= "account"),
@SqlFragmentAlias( alias = "ad", table= "account_details"),
}
)
public static class Account {

@Id
private Long id;

private Double amount;

private Double rate;

private boolean active;

@Column(table = "account_details")
private boolean deleted;

//Getters and setters omitted for brevity

}
Now, when fetching the Account entities and activating the filter, Hibernate is going to apply the right table aliases to the filter predicates.

No comments:

Post a Comment