【发布时间】:2023-02-03 02:11:43
【问题描述】:
我有一个典型的 Spring boot(2.7.6) 应用程序,带有用于获取数据的 api科特林.
假设一个名为 Employee 的实体
@Entity
data class Employee(
val id: Long,
val name: String,
val age: Int,
val interviewDate: LocalDate,
val joiningDate: LocalDate,
val resignationDate: LocalDate,
val lastWorkingDate: LocalDate
)
为了简洁起见,我从上面的实体类中删除了 @Id 等注释。
出售员工数据的 API 之一是这样的,在请求参数我得到类似 dateType 的内容,它将包含 interviewDate/joiningDate/resignationDate/lastWorkingDate 之一。在请求参数dateFrom和dateTo中,我将日期作为输入,如2020-10-01和2022-12-30
例如,如果 api 获得类似 dateType=interviewDate&dateFrom=2020-10-01&dateTo=2022-12-30 的输入,则 API 必须返回其 interview_date 列的值介于 2020-10-01 和 2022-12-30 之间的所有员工记录
上面给出的示例只是为了便于说明。对于实际用例,必须从许多表中获取数据并具有许多连接(内/左/右)。
根据输入,在存储库方法中动态选择列的更好方法是什么?
我试过了规格标准 API,但这是一个死胡同,因为我不能使用 joins,因为实体之间没有映射,如 @OneToMany 等。
我正在尝试使用 @Query 来获取数据,但必须为每个条件复制大量的 sql 行。
我在存储库类中编写的其中一个查询示例如下所示:
@Query(
"""
select
t.a as A,
t.b as B,
tt.c as C,
p.d as D,
p.e as E
from Employee p
join Department t on p.some_id = t.id
join PersonalData tt on tt.id = t.some_id
left outer join SalaryInformation ps on p.id = ps.come_id
left outer join ManagerInformation sbt on p.some_id = sbt.id
. few more joins here
.
.
where p.id= :id and p.interviewDate>=:dateFrom and p.interviewDate<=:dateTo
""" ,
nativeQuery = true
)
fun findByEmployeeIdForInterviewDate(employeeId: Long, dateFrom:String, dateTo: String, pageable: Pageable): Slice<EmployeeDetailsProjection>
使用当前方法,我必须对剩余的日期列重复此查询,因为它看起来很难看。
任何更好的建议都会很有帮助:)
【问题讨论】:
标签: spring-boot hibernate jpa spring-data-jpa spring-data