简体   繁体   English

如何从 Hibernate 调用 MySQL 存储过程

[英]How to call a MySQL stored procedure from Hibernate

I am trying to call a MySQL stored procedure from Java Application which uses MySQL.我正在尝试从使用 MySQL 的 Java 应用程序调用 MySQL 存储过程。 Below is the part in DAO where i used to call a stored procedure 'insertComm'下面是 DAO 中我用来调用存储过程“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)) 'opt' 值显示为 SQLQueryImpl(CALL insertComm (:remitNo, :opt))

The parameter is okay and application is not showing error also.参数没问题,应用程序也没有显示错误。 I can't see what i missed.我看不到我错过了什么。

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 :您可以使用 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:如果您的存储过程返回REFCURSORTABLE结果:

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:对于数据库函数,返回结果集而不是将其放在OUT变量中:

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: Hibernate 4.x 和 5.x API 对您没有帮助,您必须改用 JDBC:

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

Unfortunately you can't call a Stored Procedure using Session.createSQLQuery() .不幸的是,您不能使用Session.createSQLQuery()调用存储过程。 As the name suggests it allows to create a SQL Query .顾名思义,它允许创建 SQL查询 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();

您没有将 Entity 添加到会话对象中... .addEntity(classname.class).setParameter()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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