Skip to content

Quick Start

Kazuki Shimizu edited this page Nov 26, 2022 · 15 revisions

Let's create a MyBatis Spring Boot Application with MyBatis Spring Native quickly using the SPRING INITIALIZR.

Pre conditions

You need to install GraalVM and need to following environment variables are defined.

  • JAVA_HOME
  • GRAALVM_HOME

Build on Docker container

Also, you can use the Docker container for building following demo application.

NOTE:

At least, 5GB+ memory need to assign to Docker. If occurred the 'Error: Image build request failed with exit status 137', please increase the memory size that assign to Docker.

Run the container.

docker run -v $(pwd):/work -v $HOME/.m2:/root/.m2 -it -w /work \
  -e JAVA_HOME=/opt/graalvm-ce-java17-22.3.0 \
  -e GRAALVM_HOME=/opt/graalvm-ce-java17-22.3.0 \
  -e LANG=C.utf8 \
  ghcr.io/graalvm/graalvm-ce:22.3.0 bash

Create a project

Create a Spring Boot standalone application for MyBatis + H2 Database using following command (or the SPRING INITIALIZR UI).

curl -s https://start.spring.io/starter.tgz\
     -d name=mybatis-sample\
     -d artifactId=mybatis-sample\
     -d dependencies=mybatis,h2,native\
     -d baseDir=mybatis-sample\
     | tar -xzvf - && cd mybatis-sample

Adding mybatis-spring-native artifact

Open pom.xml file and adding mybatis-spring-native-core as dependency artifact.

<dependency>
  <groupId>org.mybatis.spring.native</groupId>
  <artifactId>mybatis-spring-native-core</artifactId>
  <version>0.1.0-SNAPSHOT</version>
</dependency>

If you use the SNAPSHOT version, please add Sonatype OSS snapshot repository as follow:

<repository>
  <id>sonatype-oss-snapshots</id>
  <name>Sonatype OSS Snapshots Repository</name>
  <url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>

Create sql files

Create a sql file(src/main/resources/schema.sql) to generate the city table.

CREATE TABLE city
(
  id      INT PRIMARY KEY auto_increment,
  name    VARCHAR,
  state   VARCHAR,
  country VARCHAR
);

Create a domain class

Create the City class(src/main/java/com/example/mybatissample/City.java).

package com.example.mybatissample;

public class City {

  private Long id;
  private String name;
  private String state;
  private String country;

  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getState() {
    return this.state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public String getCountry() {
    return this.country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  @Override
  public String toString() {
    return getId() + "," + getName() + "," + getState() + "," + getCountry();
  }

}

Create a mapper interface

Create the CityMapper interface(src/main/java/com/example/mybatissample/CityMapper.java) for annotation driven.

package com.example.mybatissample;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface CityMapper {

  @Insert("INSERT INTO city (name, state, country) VALUES(#{name}, #{state}, #{country})")
  @Options(useGeneratedKeys = true, keyProperty = "id")
  void insert(City city);

  @Select("SELECT id, name, state, country FROM city WHERE id = #{id}")
  City findById(long id);

}

Modify a spring boot application class

Add a bean definition that implements the CommandLineRunner interface at the MybatisSampleApplication class(src/main/java/com/example/mybatissample/MybatisSampleApplication.java) and call a mapper method.

package com.example.mybatissample;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MybatisSampleApplication {

  public static void main(String[] args) {
    SpringApplication.run(MybatisSampleApplication.class, args);
  }

  private final CityMapper cityMapper;

  public MybatisSampleApplication(CityMapper cityMapper) {
    this.cityMapper = cityMapper;
  }

  @Bean
  CommandLineRunner sampleCommandLineRunner() {
    return args -> {
      City city = new City();
      city.setName("San Francisco");
      city.setState("CA");
      city.setCountry("US");
      cityMapper.insert(city);
      System.out.println(this.cityMapper.findById(city.getId()));
    };
  }

}

Run a spring boot application

Run a created application using the Spring Boot Maven Plugin.

Using spring-boot:run

./mvnw spring-boot:run
2022-01-31 12:37:31.090  INFO 48697 --- [           main] o.s.nativex.NativeListener               : AOT mode disabled

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (vx.x.x)

...
2022-01-31 12:37:31.789  INFO 48697 --- [           main] c.e.m.MybatisSampleApplication           : Started MybatisSampleApplication in 0.91 seconds (JVM running for 1.185)
1,San Francisco,CA,US
...

Using native-image and executable jar

Also, you can package to a native-image and a jar file as follow:

./mvnw package -Pnative -DskipTests

Run with native-image as follow:

./target/mybatis-sample
2022-01-31 12:33:29.617  INFO 48665 --- [           main] o.s.nativex.NativeListener               : AOT mode enabled

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (vx.x.x)

...
2022-01-31 12:33:29.640  INFO 48665 --- [           main] c.e.m.MybatisSampleApplication           : Started MybatisSampleApplication in 0.034 seconds (JVM running for 0.036)
1,San Francisco,CA,US
...

Run with executable jar as follow:

java -jar target/mybatis-sample-0.0.1-SNAPSHOT-exec.jar
2022-01-31 12:35:36.375  INFO 48677 --- [           main] o.s.nativex.NativeListener               : AOT mode disabled

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (vx.x.x)

...
2022-01-31 12:35:37.526  INFO 48677 --- [           main] c.e.m.MybatisSampleApplication           : Started MybatisSampleApplication in 1.459 seconds (JVM running for 1.902)
1,San Francisco,CA,US
...