我正在使用Spring MVC 4,Hibernate和Postgresql 9.3,并在Postgres中定义了函数(存储过程),如下所示:
CREATE OR REPLACE FUNCTION spa.create_tenant(t_name character varying)
RETURNS void AS
$BODY$
BEGIN
EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I AUTHORIZATION postgres',t_name);
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION spa.create_tenant(character varying)
OWNER TO postgres;
如果我像这样在pgAdmin中运行此函数它工作正常:
select spa.create_tenant('somename');
现在我正试图从我的服务运行这个功能,如下所示:
@Override
@Transactional
public void createSchema(String name) {
StoredProcedureQuery sp = em.createStoredProcedureQuery("spa.create_tenant");
sp.registerStoredProcedureParameter("t_name",String.class,ParameterMode.IN);
sp.setParameter("t_name",name);
sp.execute();
}
javax.persistence.PersistenceException: org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111
我猜这是因为在函数中定义的返回类型void所以我将返回类型更改为如下所示:
RETURNS character varying AS
如果我再次运行我的方法,我会得到这个例外:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Error calling CallableStatement.getMoreResults
最佳答案
在你的实体类中,定义一个NamedNativeQuery,就像你用select调用postgresql函数一样.
原文链接:https://www.f2er.com/spring/431526.htmlimport javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.Entity;
@NamedNativeQueries(
value={
// cast is used for Hibernate,to prevent No Dialect mapping for JDBC type: 1111
@NamedNativeQuery(
name = "Tenant.createTenant",query = "select cast(create_tenant(?) as text)"
)
}
)
@Entity
public class Tenant
hibernate无法映射void,因此解决方法是将结果转换为文本
public void createSchema(String name) {
Query query = em.createNamedQuery("Tenant.createTenant")
.setParameter(1,name);
query.getSingleResult();
}