Hibernate CrudRepository本机查询不使用to_timestamp函数返回结果

时间:2019-04-25 12:21:45

标签: hibernate jpa

我正在使用oracle作为数据库。我需要编写一个本机查询并将结果存储为列表。我尝试运行的本机查询可以使用sqldeveloper工具完美运行。但是当我用CrudRepository尝试时,结果返回一个空列表。 我基本上是在尝试检索我们所处当月的数据。

created_at是数据库中的时间戳记字段

下面是我的代码

@Repository
public interface TestRepository extends CrudRepository<City, Long> {

    @Query(value = "SELECT * FROM (SELECT plate,SUM(TOTAL_PRICE) as total FROM sale_item_ok where company_id =2 and created_at >= TO_TIMESTAMP (TRUNC(sysdate,'mm'),'DD/MM/YYYY') and created_at < TO_TIMESTAMP (TRUNC(add_months(sysdate,1),'mm'),'DD/MM/YYYY') group by plate order by total desc) WHERE ROWNUM<=5"
                   , nativeQuery = true)
    List<item> findCustomVehicles();

}

投影界面

public interface item{

    String getPlate();
    int getTotal();
}

作为起点,我认为冬眠的to_timestamp方法中存在问题。当我更新如下所示的where条件并删除to_timestamp部分时,它工作正常并返回结果。

@Repository
public interface TestRepository extends CrudRepository<City, Long> {

    @Query(value = "SELECT * FROM (SELECT plate,SUM(TOTAL_PRICE) as total FROM sale_item_ok where company_id =2 group by plate order by total desc) WHERE ROWNUM<=5"
                   , nativeQuery = true)
    List<item> findCustomVehicles();

}

1 个答案:

答案 0 :(得分:0)

您可以尝试一次吗? 使用方法 createNativeQuery(sqlString,resultClass) 还可以使用EntityManager.createNativeQuery()

动态定义本机查询。
String sql = "YOUR_QUERY WHERE ID = ?";
Query query = em.createNativeQuery(sql, item.class);
query.setParameter(1, id);
item itemObj= (item) query.getSingleResult();
相关问题