2020-08-27

Hibernate JPA @WhereJoinTable Example

@WhereJoinTable

The @WhereJoinTable annotation is used to specify a custom SQL WHERE clause used when fetching a join collection table.

WhereJoinTable Where clause to add to the collection join table. The clause is written in SQL. Just as with Where, a common use case is for implementing soft-deletes.

@WhereJoinTable
Just like @Where annotation, @WhereJoinTable is used to filter out collections using a joined table (e.g. @ManyToMany association).

Example : @WhereJoinTable mapping example

@Entity(name = "Book")
public static class Book {

@Id
private Long id;

private String title;

private String author;

@ManyToMany
@JoinTable(
name = "Book_Reader",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "reader_id")
)
@WhereJoinTable( clause = "created_on > DATEADD( 'DAY', -7, CURRENT_TIMESTAMP() )")
private List<Reader> currentWeekReaders = new ArrayList<>( );

//Getters and setters omitted for brevity

}

@Entity(name = "Reader")
public static class Reader {

@Id
private Long id;

private String name;

//Getters and setters omitted for brevity

}

No comments:

Post a Comment