fukit0
fukit0

Reputation: 974

Joining two table entities in Spring Data JPA with where clause

I have been searching the answer for my question below, and nothing come up so far.

Quick explanation:

A person can has more than one roles, and role has many-to-many relationship with privilege.

I have the entities, Role:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "ROLE")
@Where(clause = "RECORD_STATUS = 'A'")
@SQLDelete(sql = "UPDATE ROLE SET RECORD_STATUS = 'D' where OBJID = ?")
public class Role extends BaseEntity implements Serializable {

   private String roleDescription;
   private String roleName;



   @JoinTable(
        name = "ROLE_PRIVILEGE",
        joinColumns = @JoinColumn(
                name = "roleOid"
        ),
        inverseJoinColumns = @JoinColumn(
                name = "privilegeOid"
        )
    )
    @Where(clause = "RECORD_STATUS = 'A'")
    @ManyToMany(fetch = FetchType.EAGER)
    List<Privilege> privileges;
}

Privilege entity:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "PRIVILEGE")
@Where(clause = "RECORD_STATUS = 'A'")
@SQLDelete(sql = "UPDATE PRIVILEGE SET RECORD_STATUS = 'D' where OBJID = ?")
public class Privilege extends BaseEntity implements Serializable {

   private String description;
   private String privilegeName;



}

I wanted to join these 2 tables like this:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "ROLE_PRIVILEGE")
@Where(clause = "RECORD_STATUS = 'A'")
@SQLDelete(sql = "UPDATE ROLE_PRIVILEGE SET RECORD_STATUS = 'D' where OBJID 
= ?")
public class RolePrivilege extends BaseEntity implements Serializable {

   private String roleOid;
   private String privilegeOid;

}

The problem is, when I try to get roles of a person, they all come with the privileges. But, hibernate doesnt care the where clause in ROLE_PRIVILEGE entitiy:

select
 privileges0_.role_oid as role_oid8_23_0_,
 privileges0_.privilege_oid as privileg7_23_0_,
 privilege1_.objid as objid1_21_1_,
 privilege1_.creation_date as creation2_21_1_,
 privilege1_.last_change_date as last_cha3_21_1_,
 privilege1_.luc as luc4_21_1_,
 privilege1_.record_status as record_s5_21_1_,
 privilege1_.user_created as user_cre6_21_1_,
 privilege1_.description as descript7_21_1_,
 privilege1_.privilege_name as privileg8_21_1_
from
 role_privilege privileges0_
 inner join
  privilege privilege1_
   on privileges0_.privilege_oid=privilege1_.objid
where
(
  privilege1_.RECORD_STATUS = 'A'
)
and privileges0_.role_oid=?

I mean, when I deactivate a role-privilege tuple(role does not have that privilege anymore), still comes to me. Where can I add the @where clause to ROLE_PRIVILEGE table to?

all advises are much appriciated!

Upvotes: 0

Views: 5849

Answers (1)

fukit0
fukit0

Reputation: 974

I do not really know how I missed that but found the solution.

@WhereJoinTable(clause = "RECORD_STATUS = 'A' ")

JPA @JoinTable with extra join conditions

Upvotes: 1

Related Questions