java Spring Data JPA 如何传递日期参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26024016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:09:09  来源:igfitidea点击:

Spring Data JPA How to pass a date parameter

javaspringspring-mvcjpaspring-data

提问by stackUser2000

I'm working in a spring MVC project and spring data with spring tools suite, I want to pass a date argument to a native query, I have this so far.

我正在使用 spring 工具套件在 spring MVC 项目和 spring 数据中工作,我想将日期参数传递给本机查询,到目前为止我已经有了。

My query method inside a interface that extends JpaRepository

我在扩展 JpaRepository 的接口中的查询方法

 @Query(value  = 
            "SELECT "
                + "a.name, a.lastname
            + "FROM "
                + "person  a, "
                + "myTable b "
            + "WHERE "
            + "a.name= ?1' "
            + "AND a.birthday = ?2 ",
         nativeQuery = true)
    public ArrayList<Object> personInfo(String name, String dateBirthDay);

The method that implements this interface definition:

实现这个接口定义的方法:

public ArrayList<Object> getPersonsList(String name, String dateBirthDay) {

            ArrayList<Object> results= null;

            results= serviceAutowiredVariable.personInfo(name, dateBirthDay);

            return results;
        }

and this is how I call it from my controller class.

这就是我从控制器类中调用它的方式。

personsList= _serviceAutowiredVariable.getPersonsList("Hyman", "TO_DATE('01-08-2013', 'DD-MM-YYYY')" );

I suppose that in this line "AND a.birthday = ?2 "the ?2is equals to this string TO_DATE('01-08-2013', 'DD-MM-YYYY')

我想,在这条线"AND a.birthday = ?2 "?2是等于该字符串TO_DATE('01-08-2013', 'DD-MM-YYYY')

but I am getting this error when I run my code

但是当我运行我的代码时出现这个错误

    [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.DataException: could not extract ResultSet; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not extract ResultSet] root cause
java.sql.SQLDataException: ORA-01858: a non-numeric character was found where a numeric was expected

ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ORA-01858: a non-numeric character was found where a numeric was expected

回答by przemek hertel

You can use such construction:

您可以使用这样的结构:

import org.springframework.data.repository.query.Param;
...

@Query(value  = 
    " SELECT a.id, a.lastname FROM person a" + 
    " WHERE a.name = :name AND a.birthday = :date ", nativeQuery = true)
public List<Object[]> getPersonInfo(
    @Param("name") String name, 
    @Param("date") Date date);