How to properly call PostgreSQL functions (stored procedures) within Spring/Hibernate/JPA?

前端 未结 6 1331
孤城傲影
孤城傲影 2021-01-12 04:11

I\'m using Spring MVC 4, Hibernate and PostgreSQL 9.3 and have defined function (stored procedure) inside Postgres like this:

CREATE OR REPLACE FUNCTION spa.         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 04:39

    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 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();
    }
    

提交回复
热议问题