如何制作一个select语句或过滤一个嵌套在一个实体中的List?我有一个看起来像这样的对象......
@Entity
@Table(name = "employee")
public class Employee {
...
@OneToMany(mappedBy = "_employee", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
@JsonManagedReference
Set<Deal> _deals;
@OneToMany(mappedBy = "_employee", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
@JsonManagedReference //This is simply to avoid a stackoverflow error according to this link http://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue
Set<Recommendation> _recommendations;
@OneToMany(mappedBy = "_employee", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
@JsonManagedReference //This is simply to avoid a stackoverflow error according to this link http://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue
Set<Event> _events;
public Employee() {
}
//getters and setters
....
我让员工拥有一个由服务类访问的存储库。
存储库看起来像这样。
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
public Employee getEmployeeById(Long _id);
public Employee getEmployeeBy_username(String username);
}
因此,当我通过其ID获得员工时,它会返回上面的列表。检索员工时,我需要以某种方式执行select语句或过滤_deals,_recommendations和_events。这样只有那些具有布尔属性_active = true的人才会返回。就像现在一样,所有交易建议和事件都会被返回,无论它们是否有效。如何过滤或从这些列表中仅选择活动对象?
答案 0 :(得分:1)
您几乎总是为每个查询选择一个实体类型,最好是在数据库中进行过滤。如果您想要属于特定员工的交易,建议和事件,我通常会将这些方法放在属于实体类型I的存储库中,并尝试加载,它可能如下所示:
@Repository
public interface DealRepository extends JpaRepository<Deal, Long> {
@Query("select d from Deal d where d.active= true and d.employee.id = :employeeId")
List<Deal> findActiveDeals(@Param("employeeId") long employeeId);
}