I'm trying to call a stored procedure on a PostgreSQL db. The procedure handles inserting, updating, and deleting table entries, so it accepts params. Some of the params are sometimes null, depending on the kind of operation you want to perform. I was able to call the proc using Hibernate's SessionFactory, but now I want to use the JPA EntityManager. The procedure using SessionFactory is as follows:
public Result callFunction(String type_proc, String node, String fullcode, Date bdate){
Session session = this.sessionFactory.getCurrentSession();
org.hibernate.Query query = session.createSQLQuery(
"SELECT*FROM public.someFunction(:type_proc, :node, :fullcode, :bdate, CAST(:cat_id AS BIGINT)")
.addEntity(Result.class)
.setParameter("type_proc", type_proc)
.setParameter("node", node)
.setParameter("fullcode", fullcode)
.setParameter("bdate", bdate)
.setParameter("cat_id", null, LongType.INSTANCE)
return (Result) query.uniqueResult();
}
As you can see, I specify the type of the field twice: one for Java, one for Postgres. Now if I do the same using the EntityManager, there is no setParameter method that accepts LongType.INSTANCE as an argument. Is there any workaround to this?
EDIT: Also looking for a way to do this using jdbcTemplate. Tried doing this way: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html#jdbc-simple-jdbc-call-1, but got a NullPointerException on the .execute(in) line.
答案 0 :(得分:0)
可能应该使用EntityManager.createStoredProcedureQuery
。通过这种方式,您可以设置参数类型,例如:
private final static String STORED_PROCEDURE = "public.someFunction";
StoredProcedureQuery query = em.createStoredProcedureQuery(STORED_PROCEDURE);
query.
registerStoredProcedureParameter(1, String.class, ParameterMode.IN).setParameter(1, type_proc).
registerStoredProcedureParameter(2, String.class, ParameterMode.IN).setParameter(2, node).
registerStoredProcedureParameter(3, String.class, ParameterMode.IN).setParameter(3, fullcode).
registerStoredProcedureParameter(4, Date.class, ParameterMode.IN).setParameter(4, bdate).
registerStoredProcedureParameter(5, LongType.INSTANCE, ParameterMode.IN).setParameter(5, null).
execute();
我使用EntityManager.createStoredProcedureQuery
代替Oracle可能会帮助您。