Hibernate JPA @Where Example

@Where

The @Where annotation is used to specify a custom SQL WHERE clause used when fetching an entity or a collection.

Where clause to add to the element Entity or target entity of a collection. The clause is written in SQL. A common use case here is for soft-deletes.

@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

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation