我怎样才能在JPA中“创建功能”

时间:2016-05-03 16:16:29

标签: postgresql jpa

我需要在JPA中创建一个动态函数,如下所示:

Query query = em.createNativeQuery("CREATE FUNCTION func() ...");`

然后我调用query.getSingleResult(),我可以在postgreSql中找到该函数,但我也得到异常:

Caused by: org.postgresql.util.PSQLException: No results were returned by the query.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:303)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:1009)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:644)

那么我能做些什么来阻止这个例外?执行非select / update / insert语句时可能会发生同样的异常。

2 个答案:

答案 0 :(得分:0)

尝试这样做:

em.getTransaction().begin();
query.executeUpdate();
em.getTransaction().commit();

编辑2: 根据@figo,这不会使用JTA。用em.getTransaction().begin()替换em.joinTransaction()似乎可以解决问题。

答案 1 :(得分:0)

我修改了我的ServletContextListener实现类,如下所示:

public class SomeListener implements ServletContextListener {

    @Resource
    UserTransaction utx;

    @PersistenceContext(unitName = "persistUnit")
    private EntityManager em;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        utx.begin();

        // It's important to fix 
        // 'the EntityManager has not been joined to the current transaction.'
        em.joinTransaction(); 

        Query query = em.createNativeQuery("CREATE FUNCTION func() ...");
        query.executeUpdate();

        utx.commit();
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }
}

这可行。