如何使用JPA和Hibernate调用具有多个OUT参数的MySQL存储过程?

时间:2016-02-07 22:08:31

标签: java mysql hibernate stored-procedures

我只使用OUT参数跟踪Mysql存储过程,如何通过仅使用OUT参数的hibernate调用此存储过程?

Session session = HibernateUtil.getSessionFactory().openSession();

Connection connection = session.connection();
CallableStatement callable = null;

try {

callable = connection.prepareCall("{Call DBNAME.getStatistics(?,?,?)}");

// three ?,?,? means three OUT parameter. 
// If any parameters is IN type of
// Lets say the first one then use : callable.setInt(1, 10);

    callable.registerOutParameter(1, Types.BIGINT);
    callable.registerOutParameter(2, Types.BIGINT);
    callable.registerOutParameter(3, Types.BIGINT);
    callable.executeUpdate();

    int value1 = callable.getInt(1);
    int value2 = callable.getInt(2);
    int value3 = callable.getInt(3);


    System.out.println(value1);
    System.out.println(value2);
    System.out.println(value3);
   } catch (SQLException e) {
       e.printStackTrace();
 }

修改

以下代码我在java中用来通过hibernate(Java)测试MySQL存储过程(只有OUT参数)的调用:

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"/>

2 个答案:

答案 0 :(得分:0)

我认为你不能用Hibernate做到这一点。我在

之前看到过这个
Connection connection = session.connection();
CallableStatement callable = null;
callable = connection.prepareCall("execute [procedure] ?");
callable.registerOutParameter(1, Types.INTEGER);
callable.execute();
int id = callable.getInt(1);

哪个有效。有关更多上下文,请参阅Retrieving a value from Stored Procedure using Native SQL Hibernate

答案 1 :(得分:0)

我写了一篇关于how you can call MySQL stored procedures and database functions from Hibernate的非常详细的文章,但我也会在这里写一篇简短的摘要。

StoredProcedureQuery query = entityManager
.createStoredProcedureQuery("getStatistics")
.registerStoredProcedureParameter("A", Long.class, ParameterMode.OUT)
.registerStoredProcedureParameter("B", Long.class, ParameterMode.OUT)
.registerStoredProcedureParameter("C", Long.class, ParameterMode.OUT);

query.execute();

Long a = (Long) query.getOutputParameterValue("A");
Long b = (Long) query.getOutputParameterValue("B");
Long c = (Long) query.getOutputParameterValue("C");