查找由集合中的相关实体过滤的实体 [英] Find entity filtered by a related entity that is in a collection
问题描述
我将Spring Data JPA用于我的存储库层,并将Spring安全性用作我的安全性层.在我的项目中,部门和员工之间具有以下单向一对多关系.以下是这两个实体的摘要.
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.
我的问题是,如何使用spring数据查询方法或jpql根据当前登录的用户(即登录的当前用户必须通过用户名字段匹配1个Employee对象)过滤掉Department实体?
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?
推荐答案
我想出了如何通过Spring Data JPA @Query方法满足我的要求的方法,而不必与Employee对象(而只是用户名)进行比较.
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)
这篇关于查找由集合中的相关实体过滤的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!