0

I am trying to call a MySQL stored procedure from Java Application which uses MySQL. Below is the part in DAO where i used to call a stored procedure 'insertComm'

String opt="REFUND";
        Query query = this.getSession().createSQLQuery("CALL insertComm (:remitNo,     :opt)")
           .setParameter("remitNo", remitNo)
               .setParameter("opt", opt);
opt=query.toString();
hemappLogger.info(opt);

But as i query the database and check, the stored procedure hasn't been executed. The 'opt' value is shown as SQLQueryImpl(CALL insertComm (:remitNo, :opt))

The parameter is okay and application is not showing error also. I can't see what i missed.

3 Answers 3

3

Considering you have a simple stored procedure that outputs a basic type:

CREATE PROCEDURE count_comments (
   IN postId INT, 
   OUT commentCount INT
) 
BEGIN
    SELECT COUNT(*) INTO commentCount 
    FROM post_comment  
    WHERE post_comment.post_id = postId; 
END

You can call this stored procedure using a JPA StoredProcedureQuery:

StoredProcedureQuery query = entityManager
    .createStoredProcedureQuery("count_comments")
    .registerStoredProcedureParameter(
        "postId", Long.class, ParameterMode.IN)
    .registerStoredProcedureParameter(
        "commentCount", Long.class, ParameterMode.OUT)
    .setParameter("postId", 1L);
 
query.execute();
 
Long commentCount = (Long) query
    .getOutputParameterValue("commentCount");

If your stored procedure returns a REFCURSOR or a TABLE result:

CREATE PROCEDURE post_comments(IN postId INT) 
BEGIN
    SELECT *  
    FROM post_comment   
    WHERE post_id = postId;  
END

You need to call the stored procedure as follows:

StoredProcedureQuery query = entityManager
    .createStoredProcedureQuery("post_comments");
query.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN);
 
query.setParameter(1, 1L);
 
List<Object[]> postComments = query.getResultList();

For database functions, that return the result set instead of placing it in an OUT variable:

CREATE FUNCTION fn_count_comments(postId integer)
RETURNS integer
DETERMINISTIC 
READS SQL DATA 
BEGIN
    DECLARE commentCount integer; 
    SELECT COUNT(*) INTO commentCount 
    FROM post_comment  
    WHERE post_comment.post_id = postId; 
    RETURN commentCount; 
END

The Hibernate 4.x and 5.x API will not help you, and you have to use JDBC instead:

int commentCount = session.doReturningWork(connection -> {
    try (CallableStatement function = connection.prepareCall(
            "{ ? = call fn_count_comments(?) }")) {
        function.registerOutParameter(1, Types.INTEGER);
        function.setInt(2, 1);
        function.execute();
        return function.getInt(1);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

do you know how to fetch particular columns from mysql db with hibernate and stored procedure
2

Unfortunately you can't call a Stored Procedure using Session.createSQLQuery(). As the name suggests it allows to create a SQL Query. A procedure call is not a query.

But fear not, the work around is this.

Connection conn = getSession().connection();
CallableStatment stat = conn.prepareCall("{CALL insertComm (?,?)}");
stat.setString(1, remitNo); // Assuming both parameters are String
stat.setString(2, opt);

stat.executeUpdate();
stat.close();

5 Comments

Thanks a lot.But i refered to link and here it users createSqlquery. may be i'm getting something not propery.
Yes, that link uses a Function (GetStocks) not a Procedure. Functions return something back to the caller. But in your case as your name suggests it is just trying to insert some values. GetStocks function will return all the stocks which matches the stock_code sent in as an argument. And since There is already a table mapping for stock (Stock class) in that example it is possible.
@shazin how to get session from getSession() here??? I am using hibernate 4.2.2.Final.I am using sessionFactory.getCurrentSession() to get the hibernate session,but here session doesn't have a method connect(). Please reply...
@shazin what is the library for CallableStatment ?? Is it com.mysql.jdbc or java.sql ???
@KJEjava48 java.sql
1

You didn't add Entity to your session object... .addEntity(classname.class).setParameter()

2 Comments

I am new with these things and donot know if it is mandatory. is it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.