英文:
How to get server messages (raise notice) from PostgreSQL function that was invoked through MyBatis mapper method?
问题
运行普通的JDBC语句时,通过PostgreSQL函数中的raise notice
命令产生的输出消息可以通过Statement.getWarnings()
进行获取,例如:
try (CallableStatement callableStatement = connection.prepareCall("select my_func()")) {
callableStatement.execute();
// ... 处理输出 ...
SQLWarning sqlWarning = callableStatement.getWarnings();
while (sqlWarning != null) {
System.out.println(sqlWarning.getMessage());
sqlWarning = sqlWarning.getNextWarning();
}
}
在运行MyBatis映射器方法后,是否有一种方法可以获取相同的输出,而不需要使用原始的JDBC方式?
英文:
When running a plain JDBC statement, the output messages produced through raise notice
commands in a PostgreSQL function can be fetched using Statement.getWarnings()
, e.g.:
try (CallableStatement callableStatement = connection.prepareCall("select my_func()")) {
callableStatement.execute();
// ... do something with the output ...
SQLWarning sqlWarning = callableStatement.getWarnings();
while (sqlWarning != null) {
System.out.println(sqlWarning.getMessage());
sqlWarning = sqlWarning.getNextWarning();
}
}
Is there a way to fetch that same output after running a MyBatis mapper method, without resorting to raw JDBC?
答案1
得分: 2
除非有更好的选择,否则我能够使用MyBatis拦截器获取该输出。拦截器代码如下:
@Intercepts({
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class})})
public class FetchStatementWarningsInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
if (args == null || args.length != 1 || !(args[0] instanceof Statement)) {
return invocation.proceed();
}
Statement statement = (Statement) args[0];
Object result = invocation.proceed();
if (!statement.isClosed()) {
SQLWarning sqlWarning = statement.getWarnings();
// ... 对警告输出进行处理 ...
}
return result;
}
}
英文:
Unless a better option is suggested, I was able to fetch that output using a MyBatis interceptor. The interceptor code:
@Intercepts({
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class})})
public class FetchStatementWarningsInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
if (args == null || args.length != 1 || !(args[0] instanceof Statement)) {
return invocation.proceed();
}
Statement statement = (Statement) args[0];
Object result = invocation.proceed();
if (!statement.isClosed()) {
SQLWarning sqlWarning = statement.getWarnings();
// ... do something with the warnings output ...
}
return result;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论