Hibernate JPA @Where Example

@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.

@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

}

@Entity(name = "Account")
@Where( clause = "active = true" )
public static class Account {

@Id
private Long id;

@ManyToOne
private Client client;

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

private Double amount;

private Double rate;

private boolean active;

//Getters and setters omitted for brevity

}

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations