【问题标题】:Hibernate CrudRepository native query not returning result with to_timestamp functionHibernate CrudRepository 本机查询不使用 to_timestamp 函数返回结果
【发布时间】:2019-04-25 12:21:45
【问题描述】:

我正在使用 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();

}

【问题讨论】:

    标签: hibernate jpa


    【解决方案1】:

    你可以试试这个吗? 使用方法 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();
    

    【讨论】:

    • 你好,我尝试了 createNativeQuery 但不幸的是 to_timestamp 仍然没有运气
    • @blackened8333,你能提供你数据库中数据的截图吗?以便我了解您在表中的数据类型以及您的转换方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    相关资源
    最近更新 更多