如何在 spring 中创建 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 获取员工时,它会返回上述列表。当检索员工时,我需要以某种方式执行选择语句或过滤_deals、_recommendations 和_events。这样只有那些具有 boolean 属性 _active=true 的返回。就像现在一样,所有交易推荐和事件都会返回,无论它们是否处于 Activity 状态。如何从这些列表中仅过滤或选择 Activity 对象?
最佳答案
您几乎总是为每个查询选择一个实体类型,并且最好在数据库中进行过滤。如果您想要属于特定员工的交易、推荐和 Activity ,我通常会将这些方法放入属于我尝试加载的实体类型的存储库中,它可能如下所示:
@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);
}
关于java - 如何在 spring 中的对象内包含的列表上创建 select 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662926/