存储过程
/**
* 执行存储过程(无返回值)
*
* @param procedureName 存储过程名称
* @param params 参数
*/
public static void executeProcedure(String procedureName, Map<String, ?> params) {
try {
StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery(procedureName);
params.forEach((k, y) -> {
storedProcedureQuery.registerStoredProcedureParameter(k, y.getClass(), ParameterMode.IN);
storedProcedureQuery.setParameter(k, y);
});
storedProcedureQuery.execute();
} catch (Exception e) {
log.error("执行存储过程异常:" + procedureName, e);
}
}
函数
/**
* 执行函数(无返回值)
*
* @param functionName 函数名称
* @param params 参数
*/
public static void executeFunction(String functionName, List<?> params) {
try {
// 参数转换
String param = getParam(params);
// 返回指定类型的对象以允许访问特定于提供者的 API
Session session = entityManager.unwrap(Session.class);
session.doWork(
connection -> {
try (CallableStatement function = connection.prepareCall("{call " + functionName + "(" + param + ") }")) {
for (int i = 1; i <= params.size(); i++) {
// 设置参数
function.setObject(i, params.get(i-1));
}
function.execute();
}
});
} catch (Exception e) {
log.error("执行函数异常:" + functionName, e);
throw e;
}
log.info("执行函数:" + functionName);
}
/**
* 参数转换:
* @param params 参数
* @return
*/
private static String getParam(List<?> params) {
String param = "";
for (int i = 0; i < params.size(); i++) {
param += (StringUtils.isNotBlank(param) ? "," : "") + "?";
}
return param;
}
附录