且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Spring / Hibernate / JPA中正确调用PostgreSQL函数(存储过程)?

更新时间:2023-09-15 13:47:34

在实体类中,定义一个NamedNativeQuery,就像调用postgresql功能使用select。

In your entity class, define a NamedNativeQuery like you would call postgresql function with select.

import 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,因此解决方法是将结果作为文本进行转换

hibernate is not able to map void, so a workaround is to cast result as text

public void createSchema(String name) {
    Query query = em.createNamedQuery("Tenant.createTenant")
            .setParameter(1, name);
    query.getSingleResult();
}