JPA调用oracle存储函数

JPA调用oracle存储函数

Oracle stored procedures

带有返回值 简单的Oracle函数

Oracle函数

CREATE OR REPLACE **PROCEDURE** count_comments (  
   postId IN NUMBER,  
   commentCount OUT NUMBER )  
AS 
BEGIN 
    SELECT COUNT(*) INTO commentCount  
    FROM post_comment  
    WHERE post_id = postId; 
END;

JPA处理

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

query.execute();

Long commentCount = (Long) query.getOutputParameterValue(2);

注意:

1。索引中丢失 IN 或 OUT 参数

此错误是由于Oracle函数的参数值与JPA中给的不统一

还有 java中获取参数的值为NULL的情况,均可导致,需注意!!!

2.entityManager 数据源

若项目中是多数据源 ,需要添加以下标识:

 @PersistenceContext(unitName = "yourOtherEntityManagerFactory")
private EntityManager entityManager;

指定数据源

Oracle functions

Oracle function 简单小例子

Oracle

CREATE OR REPLACE FUNCTION fn_count_comments ( 
    postId IN NUMBER ) 
    RETURN NUMBER 
IS
    commentCount NUMBER; 
BEGIN
    SELECT COUNT(*) INTO commentCount 
    FROM post_comment 
    WHERE post_id = postId; 
    RETURN( commentCount ); 
END;

JPA

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

具体可参考链接

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

猜你喜欢

转载自blog.csdn.net/tel13259437538/article/details/82152405