java - 如何显示 Spring 和 MyBatis 中的 SQL 错误?

标签 java spring spring-boot spring-mybatis

我在调试器中使用 --debug 运行了以下代码,但它不会打印出任何 SQL 错误。它会默默地失败并出现异常,并从 servlet 请求中返回。

    System.out.println("sourceMapper = " + sourceMapper);
    Source source = sourceMapper.findByHost(host);
    System.out.println("source = " + source);

这是输出

2018-05-11 13:47:58.080  INFO 29392 --- [nio-8080-exec-2] c.s.shorturl.apis.ShortUrlApiController  : Method name: doUrlRequest() user agent is = curl/7.59.0
sourceMapper = org.apache.ibatis.binding.MapperProxy@30a1e904
2018-05-11 13:47:58.359  INFO 29392 --- [nio-8080-exec-2] o.s.b.f.xml.XmlBeanDefinitionReader      : Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
2018-05-11 13:47:58.489  INFO 29392 --- [nio-8080-exec-2] o.s.jdbc.support.SQLErrorCodesFactory    : SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase, Hana]
2018-05-11 13:47:58.541 DEBUG 29392 --- [nio-8080-exec-2] o.s.b.w.f.OrderedRequestContextFilter    : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@645ec595

如何打印遇到的 SQL 错误?或者找出失败的原因以及异常是什么?

MyBatis 3.4.5、MyBatis Spring 1.3.1、MyBatis Spring Boot 自动配置 1.3.1、MyBatis Spring Boot Starter 1.3.1、Spring Boot 1.5.6

最佳答案

您可以在代码周围添加 try/catch 并记录捕获的异常:

try {
    System.out.println("sourceMapper = " + sourceMapper);
    Source source = sourceMapper.findByHost(host);
    System.out.println("source = " + source);
} catch (Exception e) {
    // log using slf4j's Logger
    logger.error("An exception caught", e);
    // or print it to standard output
    e.printStackTrace();
}

某处应该有一个 Logger 实例(可能在同一个类中):

private final Logger logger = LoggerFactory.getLogger(this.getClass());

关于java - 如何显示 Spring 和 MyBatis 中的 SQL 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297784/

相关文章:

java - 在其 TreeView 中显示 ITreeContentProvider 的 "input-element"

java - Lagom 使用 Kafka 发布消息

java - Spring Boot 为自定义错误页面返回 200 状态代码

spring - Hystrix 和 Spring @Async 组合

java - 如何使用数组创建嵌套 for 循环以从 java 中的一组数字中提取特定数字?

java - 使用 JDBC 从 Oracle 获取唯一索引的所有外键

java - Spring MVC : @RequestBody when no content-type is specified

html - URL 在 CSS 中。如何绑定(bind)到当前部署的任何上下文?

java - 多个身份验证提供程序 :/j_spring_security_check and social login

spring-mvc - 无法在 Spring Boot 资源模板中加载 css