Integrate Spanner with MyBatis and Spring Boot (GoogleSQL)

MyBatis is a persistence framework with support for custom SQL and advanced mappings. MyBatis eliminates most of the JDBC code and manual setting of parameters and retrieval of results in your application.

Set up MyBatis for Spanner GoogleSQL-dialect databases

You can integrate Spanner GoogleSQL-dialect databases with MyBatis and Spring Boot using the Spanner JDBC driver.

Dependencies

In your project, add Apache Maven dependencies for MyBatis, Spring Boot, and the Spanner JDBC driver.

<dependencies>
  <!-- MyBatis and Spring Boot -->
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
  </dependency>
  <dependency>
    <groupId>org.mybatis.dynamic-sql</groupId>
    <artifactId>mybatis-dynamic-sql</artifactId>
  </dependency>

  <!-- Spanner JDBC driver -->
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-spanner-jdbc</artifactId>
  </dependency>
<dependencies>

Data source configuration

Configure application.properties to use the Spanner JDBC driver and to connect to a Spanner GoogleSQL-dialect database.

spanner.project=my-project
spanner.instance=my-instance
spanner.database=mybatis-sample

spring.datasource.driver-class-name=com.google.cloud.spanner.jdbc.JdbcDriver
spring.datasource.url=jdbc:cloudspanner:/projects/${spanner.project}/instances/${spanner.instance}/databases/${spanner.database}

Full sample application

To try this integration with a sample application, see Spring Data MyBatis Sample Application with Spanner GoogleSQL.

What's next