How to call an Oracle function from Hibernate with a return parameter?

后端 未结 5 1619
你的背包
你的背包 2020-11-29 05:47

My question is very much like Getting the return value of a PL/SQL function via Hibernate

I have a function which does some modifications internally and it returns a

5条回答
  •  执念已碎
    2020-11-29 06:16

    I wrote an article about various ways of calling Oracle stored procedures and functions from Hibernate so, to summarize it, you have the following options:

    1. With a @NamedNativeQuery:

      @org.hibernate.annotations.NamedNativeQuery(
          name = "fn_my_func",
          query = "{ ? = call MYSCHEMA.MYFUNC(?, ?) }",
          callable = true,
          resultClass = Integer.class
      )
      
      Integer result = (Integer) entityManager.createNamedQuery("fn_my_func")
          .setParameter(1, 1)
          .setParameter(2, 1)
          .getSingleResult();    
      
    2. With JDBC API:

      Session session = entityManager.unwrap( Session.class );
      
      final AtomicReference result = 
          new AtomicReference<>();
      
      session.doWork( connection -> {
          try (CallableStatement function = connection
                  .prepareCall(
                      "{ ? = call MYSCHEMA.MYFUNC(?, ?) }"
                  )
              ) {
              function.registerOutParameter( 1, Types.INTEGER );
              function.setInt( 2, 1 );
              function.setInt( 3, 1 );
              function.execute();
              result.set( function.getInt( 1 ) );
          }
      } );            
      
    3. With a native Oracle query:

      Integer result = (Integer) entityManager.createNativeQuery(
          "SELECT MYSCHEMA.MYFUNC(:postId, :transId) FROM DUAL")
          .setParameter("postId", 1)
          .setParameter("transId", 1)
          .getSingleResult();
      

提交回复
热议问题