Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createNativeQuery set parameter

I have the following that contains a NativeQuery where i need to set a parameter but somothing is wrong beacause parameter not set so the query is

SELECT movieId, title, genres FROM movies where title like '%%'"

so return all the rows. What is wrong

public List<T> findMovie(String keyword) {
        Query q = getEntityManager().createNativeQuery("SELECT movieId, title, genres FROM movies where title like '%?%'", entityClass);
        q.setParameter(1, keyword); //etc
        return q.getResultList();
    }
like image 826
Giorgos Avatar asked Feb 07 '17 17:02

Giorgos


Video Answer


1 Answers

public List<T> findMovie(String keyword) {
    Query q = getEntityManager().createQuery("SELECT movieId, title, genres FROM movies where title like :keyword", entityClass);
    q.setParameter("keyword", keyword); //etc
    return q.getResultList();
}

If you want to use positional params, use this syntax:

public List<T> findMovie(String keyword) {
    Query q = getEntityManager().createQuery("SELECT movieId, title, genres FROM movies where title like ?1", entityClass);
    q.setParameter(1, keyword); //etc
    return q.getResultList();
}
like image 180
Renats Stozkovs Avatar answered Sep 30 '22 13:09

Renats Stozkovs