Search code examples
javaspringspring-bootspring-mybatis

How do I display SQL errors from Spring and MyBatis?


I have the following code that I ran in the debugger with --debug but it won't print out any SQL errors. It fails silently with an exception and returns from the servlet request.

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

This is the output

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

How do I print the SQL errors that it is encountering? Or find out why it's failing and what the exception is?

MyBatis 3.4.5, MyBatis Spring 1.3.1, MyBatis Spring Boot Autoconfigure 1.3.1, MyBatis Spring Boot Starter 1.3.1, Spring Boot 1.5.6


Solution

  • You could add a try/catch around your code and log a caught exception:

    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();
    }
    

    There should be a Logger instance somewhere (probably in the same class):

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