问题
I'm using Spring Data JPA for my repository layer and spring security as my security layer. In my project, I have the following unidirectional one-to-many relationship between Department and Employee. Below are snippets of the 2 entities.
@Entity
public class Department {
...
@OneToMany
@JoinColumn(name="department")
private Set<Employee> members;
...
}
@Entity
public class Employee {
...
private String username;
...
}
The relationship has to be unidirectional due to certain restrictions and one of my use case is to find the department of a logged in user.
My question is, how do I filter out a Department entity based one the current user logged in (i.e. the current user logged in must match 1 Employee object via the username field) using either spring data query methods or jpql?
回答1:
Using JPQL
you can use MEMBER OF
collection predicate.
//Fetch <YOUR EMPLOYEE ENTITY TO MATCH> or
//Create an new EMPLOYEE object with its primary key prepopulated if you already know it.
Query query = SELECT d FROM Department d WHERE :employee MEMBER OF d.members
query.setParameter("employee", <YOUR EMPLOYEE ENTITY TO MATCH>);
query.list();
回答2:
I figured out how my requirement can be fulfilled via Spring Data JPA @Query approach without needing to compare with the Employee object but just the username.
@Query("select dept from Department dept inner join dept.members member where member.username = ?1")
Department findDeptByQuery(String username)
来源:https://stackoverflow.com/questions/42421938/find-entity-filtered-by-a-related-entity-that-is-in-a-collection