Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Quick Start

Kazuki Shimizu edited this pageMay 13, 2023 ·14 revisions

Let's create a MyBatis Spring Boot Application quickly using theSPRING INITIALIZR.

Create a project

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

$ curl -s https://start.spring.io/starter.tgz\       -d name=mybatis-sample\       -d artifactId=mybatis-sample\       -d dependencies=mybatis,h2\       -d baseDir=mybatis-sample\       -d type=maven-project\       | tar -xzvf -

Create sql files

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

CREATETABLEcity(  idINTPRIMARY KEY auto_increment,  nameVARCHAR,  stateVARCHAR,  countryVARCHAR);

Create a domain class

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

packagecom.example.mybatissample;publicclassCity {privateLongid;privateStringname;privateStringstate;privateStringcountry;publicLonggetId() {returnthis.id;  }publicvoidsetId(Longid) {this.id =id;  }publicStringgetName() {returnthis.name;  }publicvoidsetName(Stringname) {this.name =name;  }publicStringgetState() {returnthis.state;  }publicvoidsetState(Stringstate) {this.state =state;  }publicStringgetCountry() {returnthis.country;  }publicvoidsetCountry(Stringcountry) {this.country =country;  }@OverridepublicStringtoString() {returngetId() +"," +getName() +"," +getState() +"," +getCountry();  }}

Create a mapper interface

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

packagecom.example.mybatissample;importorg.apache.ibatis.annotations.Insert;importorg.apache.ibatis.annotations.Mapper;importorg.apache.ibatis.annotations.Options;importorg.apache.ibatis.annotations.Select;@MapperpublicinterfaceCityMapper {@Insert("INSERT INTO city (name, state, country) VALUES(#{name}, #{state}, #{country})")@Options(useGeneratedKeys =true,keyProperty ="id")voidinsert(Citycity);@Select("SELECT id, name, state, country FROM city WHERE id = #{id}")CityfindById(longid);}

Modify a spring boot application class

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

packagecom.example.mybatissample;importorg.springframework.boot.CommandLineRunner;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.annotation.Bean;@SpringBootApplicationpublicclassMybatisSampleApplication {publicstaticvoidmain(String[]args) {SpringApplication.run(MybatisSampleApplication.class,args);  }privatefinalCityMappercityMapper;publicMybatisSampleApplication(CityMappercityMapper) {this.cityMapper =cityMapper;  }@BeanCommandLineRunnersampleCommandLineRunner() {returnargs -> {Citycity =newCity();city.setName("San Francisco");city.setState("CA");city.setCountry("US");cityMapper.insert(city);System.out.println(this.cityMapper.findById(city.getId()));    };  }}

Modify a spring boot application test class

Add assertion at theMybatisSampleApplicationTests class(src/test/java/com/example/mybatissample/MybatisSampleApplicationTests.java) and call a mapper method.

packagecom.example.mybatissample;importorg.assertj.core.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.extension.ExtendWith;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.boot.test.system.CapturedOutput;importorg.springframework.boot.test.system.OutputCaptureExtension;@ExtendWith(OutputCaptureExtension.class)@SpringBootTestclassMybatisSampleApplicationTests {@TestvoidcontextLoads(CapturedOutputoutput) {Assertions.assertThat(output.getOut()).contains("1,San Francisco,CA,US");  }}

Run a spring boot application

Run a created application using the Spring Boot Maven Plugin.

$ ./mvnw spring-boot:run...  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (vx.x.x)...1,San Francisco,CA,US...

Also, you can package(with test) to a jar file and run using java command as follow:

$ ./mvnw package...1,San Francisco,CA,US[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.685 s - in com.example.mybatissample.MybatisSampleApplicationTests...
$ java -jar target/mybatis-sample-0.0.1-SNAPSHOT.jar  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (vx.x.x)...1,San Francisco,CA,US...

[8]ページ先頭

©2009-2025 Movatter.jp