简体   繁体   中英

JPA called stored procedure selecting data from 2 db

I am using mySql and jee application using jpa and hibernate

I have a stored procedure that deletes data from table in db1 then selects data from table from db2 and inserts them in table from 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

When calling in sql it succeeds When calling from jpa it returns exception

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 code:

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

The problem seems that there is selection from 2 different databases where em can't handle this operation How can i perform this task

Note : I also tried native named query and i tried @NamedStoredProcedureQuery All gave the same exception

You seem to execute the stored procedure and expect a result set in return:

query.list();

This doesn't seem correct to me, you won't be getting any records. Try calling it as if you want to run update or delete:

query.executeUpdate();

As Sva.Mu already wrote, the stored procedure call throws an exception because the entity manager expect a result from the call, if you use

query.list();

You can see it in this part of the error message

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

The call should work, if you instead use

query.executeUpdate()

In that case, the entity manager will not expect any result from the stored procedure call.

This is the same, if you use a @NamedStoredProcedureQuery or the more dynamic StoredProcedureQuery. You can read more about it on my here: @NamedStoredProcedureQuery and StoredProcedureQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM