Helio Bentzen Helio Bentzen - 2 years ago 92
Java Question

What's the best way to calling a Stored Procedure using Hibernate in a Generic DAO?

I'm using MySql and my query to call is like:

call SPGetChart (idNumber, nameChart);

Answer Source

Using EntityManager

   Query query=getEntityManager().
                           createNativeQuery("BEGIN SPGetChart(:id, :name); END;");
   query.setParameter("id", idValue);
   query.setParameter("name", nameChart);


Using connection through EntityManager:

   Connection con = ((SessionImpl) getEntityManager().getDelegate()).connection();
   CallableStatement callableStatement = cc.prepareCall("{call SPGetChart (?,?)}");

   callableStatement.setInt(1, idValue);
   callableStatement.setString(2, nameChart);

Using Session:

Query query = session.createSQLQuery("CALL SPGetChart (:id, :name)")
               .setParameter("id", idValue)
                   .setParameter("name", nameChart);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download