Spring Data JPA How to pass a date parameter

20,975

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);
Share:
20,975
stackUser2000
Author by

stackUser2000

Updated on August 08, 2022

Comments

  • stackUser2000
    stackUser2000 over 1 year

    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.

    My query method inside a interface that extends 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("Jack", "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')

    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
    
    • M. Deinum
      M. Deinum over 9 years
      Just pass a Date object instead of a String.
  • przemek hertel
    przemek hertel over 9 years
    I made typo mistake - getPersonInfo takes 2 arguments: of type String and Date of course. I have just edited to fix this.