【问题标题】:JPA called stored procedure selecting data from 2 dbJPA 调用存储过程从 2 db 中选择数据
【发布时间】:2015-09-18 18:24:24
【问题描述】:

我正在使用 jpa 和 hibernate 使用 mySql 和 jee 应用程序

我有一个存储过程,它从 db1 中的表中删除数据,然后从 db2 中的表中选择数据并将它们插入到 db1 中的表中

CREATE PROCEDURE `update_data`(myId int(11))
BEGIN
    DELETE FROM db1.tbl1
    WHERE db1.tbl1.id = myId;

    INSERT INTO
    db1.tbl1
    SELECT * FROM
    db2.tbl1
    WHERE db2.tbl1.id = myId;
END

在sql中调用时成功 从 jpa 调用时返回异常

ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-17) ResultSet is from UPDATE. No Data.
ERROR [stderr] (default task-17) org.hibernate.exception.GenericJDBCException: could not execute query

JAVA代码:

@PersistenceContext(name = "db2", unitName = "db2")
EntityManager em;

org.hibernate.Session session = (org.hibernate.Session) em.getDelegate();

        Transaction tx = null;
        tx = session.beginTransaction();
        try {
            Query query = session
                    .createSQLQuery("CALL update_teachers(:sesId)")
                    .addEntity(Teacher.class).setParameter("sesId", sesId);
            query.list();
            session.flush();
            session.clear();

            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
        session.close();
        }

问题似乎是从 2 个不同的数据库中选择 em 无法处理此操作 我该如何执行此任务

注意:我也试过native named query 我试过@NamedStoredProcedureQuery 都给出了相同的例外

【问题讨论】:

标签: java mysql sql hibernate jpa


【解决方案1】:

您似乎执行了存储过程并期望得到一个结果集:

query.list();

这对我来说似乎不正确,你不会得到任何记录。尝试调用它,就好像你想运行更新或删除一样:

query.executeUpdate();

【讨论】:

  • 问题是只返回一个异常,以防存储过程成功且没有错误,我检查了 db 并且发现了什么
【解决方案2】:

正如 Sva.Mu 已经写的那样,存储过程调用会引发异常,因为实体管理器期望调用的结果,如果您使用

query.list();

您可以在这部分错误信息中看到它

ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-17) ResultSet is from UPDATE. No Data.

如果您改为使用,调用应该可以工作

query.executeUpdate()

在这种情况下,实体管理器不会期望存储过程调用有任何结果。

如果您使用@NamedStoredProcedureQuery 或更动态的StoredProcedureQuery,这也是一样的。你可以在我这里阅读更多关于它的信息:@NamedStoredProcedureQueryStoredProcedureQuery

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多