How to call a custom Oracle function returning a value from JPA

后端 未结 5 603
暗喜
暗喜 2021-01-14 01:23

I have a custom function in oracle returning a number after deleting records. I could get a value in sql_plus such as

call my_function(4) into :out_number;
<         


        
5条回答
  •  情书的邮戳
    2021-01-14 01:45

    From https://vladmihalcea.com/how-to-call-oracle-stored-procedures-and-functions-from-hibernate/:

    First, we can simply call the Oracle function just like any other SQL query:

    BigDecimal commentCount = (BigDecimal) entityManager
        .createNativeQuery(
            "SELECT fn_count_comments(:postId) FROM DUAL"
        )
        .setParameter("postId", 1L)
        .getSingleResult();
    

    Another approach is to call the database function using plain JDBC API:

    Session session = entityManager.unwrap( Session.class );
    
    final AtomicReference commentCount = 
        new AtomicReference<>();
    
    session.doWork( connection -> {
        try (CallableStatement function = connection
                .prepareCall(
                    "{ ? = call fn_count_comments(?) }"
                )
            ) {
            function.registerOutParameter( 1, Types.INTEGER );
            function.setInt( 2, 1 );
            function.execute();
            commentCount.set( function.getInt( 1 ) );
        }
    } );
    

提交回复
热议问题