我是一名JPA新手,并且希望对单个表(如下)进行JPA本机查询,我希望在基于@Entity的类TestRequest中获取该表。它具有一列“ RequestTime”,该列通过DAYNAME()然后通过DATEDIFF()函数获取。
SELECT TestRequest.Id AS Id
, TestRequest.RequestTime AS RequestTime
, DAYNAME(TestRequest.RequestTime) AS RequestDay
, TestRequest.StatusMessage AS StatusMessage
, DATEDIFF(CURDATE(), TestRequest.RequestTime) AS HowLongAgo
FROM TestRequest
LEFT JOIN TestRun
ON TestRequest.TestRunId = TestRun.Id
WHERE Requestor = '[NAME]'
ORDER BY Id DESC
是否可以将列(第二次作为HowLongAgo获取)设置为未映射到TestRequest类中的表列的属性中?是否有任何字段级注释?
答案 0 :(得分:0)
您需要使用Interface-based projections:
您将需要创建一个接口,为您的投影中的每个字段定义吸气剂,例如:
public interface RequestJoinRunProjection {
int getId();
LocalDate getRequestTime();
String getMessage();
String getRequestDay();
Long getHowLongAgo();
}
然后,在存储库上定义一个方法,该方法具有要运行的本机查询:
public interface TestRequestRepository extends CrudRepository<TestRequest, Long> {
// Any other custom method for TestRequest entity
@Query(value = "SELECT trq.Id AS id " +
" , trq.RequestTime AS requestTime " +
" , DAYNAME(trq.RequestTime) AS requestDay " +
" , trq.StatusMessage AS statusMessage " +
" , DATEDIFF(YEAR, CURDATE(), trq.RequestTime) AS howLongAgo " +
"FROM TestRequest trq " +
" LEFT JOIN TestRun tr " +
" ON trq.TestRunId = tr.Id " +
"WHERE Requestor = ?1 ORDER BY Id DESC"), nativeQuery = true)
List<RequestJoinRunProjection> findTestSumary(String name);
}
由于您正在使用数据库函数,因此通知查询必须是本地查询,并且列名也必须与投影接口的设置器匹配(遵循bean规则),因此请使用AS
来更改查询中的名称。
我强烈建议您在注入@Query
注释之前在h2上测试查询。 DATEDIFF
需要3个参数。