0

I created a native query where I use the postgres function date_part(text, timestamp) . This is my code:

String sql = "SELECT "
                + "(SELECT coalesce(count(*), 0) FROM public.cliente) AS totalClientes, "
                + "(SELECT coalesce(count(*), 0) FROM cliente WHERE date_part('year', dt_cadastro) = date_part('year', :ano) ) AS totalNovosClientes";
                
Query query = entityManager.createNativeQuery(sql);
        query.setParameter("ano", "2021-01-01");

The problem I'm facing here is when I try to set the parameter of the date_part function. It says that I need to add explicit cast for the "ano" parameter. I've already tried the following, but none of them worked:

date_part('year', TIMESTAMP :ano)
query.setParameter("ano", "2021-01-01");
query.setParameter("ano", java.sql.Timestamp.valueOf("2021-01-01 10:10:10.0"), TemporalType.TIMESTAMP );

How to set the parameter properly?

1 Answer 1

1

JPA specification does not support named parameters with native queries,but depending on what JPA implementation you use replacing the : in your sql string with # or ? might work.

In general for native queries the best practice is to use positional based parameters, e.g:

String sql = "SELECT "
    + "(SELECT coalesce(count(*), 0) FROM public.cliente) AS totalClientes, "
    + "(SELECT coalesce(count(*), 0) FROM cliente WHERE "
    + "date_part('year', dt_cadastro) = date_part('year', $1) ) AS totalNovosClientes";
                
Query query = entityManager.createNativeQuery(sql);
query.setParameter(1, "2021-01-01");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.