'Hibernate exclude rows with condition
@Entity
public class ClassA {
some attributes
@Enumerated(value = EnumType.STRING)
private EnumObject status;
}
My Enum:
public enum EnumObject {
OK,
BAD,
SOME_CASE,
ANOTHER_CASE;
There are a possibility to say never return Entity when status=BAD for all queries
Solution 1:[1]
Kindly see if the below notions help you in achieving what you are after:
2.3.21. @Where
Sometimes, you want to filter out entities or collections using custom SQL criteria. This can be achieved using the @Where annotation, which can be applied to entities and collections.
Example 78. @Where mapping usage
public enum AccountType {
DEBIT,
CREDIT
}
@Entity(name = "Client")
public static class Client {
@Id
private Long id;
private String name;
@Where( clause = "account_type = 'DEBIT'")
@OneToMany(mappedBy = "client")
private List<Account> debitAccounts = new ArrayList<>( );
@Where( clause = "account_type = 'CREDIT'")
@OneToMany(mappedBy = "client")
private List<Account> creditAccounts = new ArrayList<>( );
//Getters and setters omitted for brevity
}
2.3.23. @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 85. @Filter mapping entity-level usage
@Entity(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
}
Also take a look at Global hibernate filter on all database queries which uses AspectJ to intercept the queries if you want to do it in another way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JCompetence |
