Hibernate annotations. @Where vs @WhereJoinTable

放肆的年华 提交于 2019-12-04 14:32:06
Igor Bljahhin

First annotation is applied on target entity. Here is very simplified example of this case in pseudo code:

@Entity
public class Role {
    private Long id;
    private boolean enabled;
}     

@Entity
public class User {
    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "USER_ROLE", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
    @Where(clause = "enabled = true")
    private Set<Role> roles = new LinkedHashSet<>(0);
}

As result only enabled roles will be populated from the database into User.roles collections.

Second annotation is applied on the association table. Below is another example in pseudo-code, but now we suppose that association table is not that trivial as in first case:

@Entity
public class Role {
    private Long id;
    private boolean enabled;
}   

@Entity
public class User {
    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "USER_ROLE", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
    @Where(clause = "enabled = true")
    @WhereJoinTable(clause = "now() between valid_from and valid_until")
    private Set<Role> roles = new LinkedHashSet<>(0);
}

and association table has validity attributes, something like 

CREATE TABLE USER_ROLE {
    ID NUMBER NOT NULL,
    USER_ID NUMBER NOT NULL,
    ROLE_ID NUMBER NOT NULL,
    VALID_FROM DATETIME,
    VALID_UNTIL DATETIME
} 

As result only enabled and valid roles will be populated from the database into User.roles collections.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!