最近項目緣由可能會繼續開始使用MyBatis,已經習慣於spring-data的風格,再回頭看xml的映射配置總以爲不是特別舒服,接口定義與映射離散在不一樣文件中,使得閱讀起來並非特別方便。java
Spring中整合MyBatis就很少說了,最近大量使用Spring Boot,所以整理一下Spring Boot中整合MyBatis的步驟。搜了一下Spring Boot整合MyBatis的文章,方法都比較老,比較繁瑣。查了一下文檔,實際已經支持較爲簡單的整合與使用。下面就來詳細介紹如何在Spring Boot中整合MyBatis,並經過註解方式實現映射。mysql
新建Spring Boot項目,或以Chapter1爲基礎來操做git
pom.xml
中引入依賴spring
這裏用到spring-boot-starter基礎和spring-boot-starter-test用來作單元測試驗證數據訪問sql
引入鏈接mysql的必要依賴mysql-connector-java數據庫
引入整合MyBatis的核心依賴mybatis-spring-boot-startermybatis
這裏不引入spring-boot-starter-jdbc依賴,是因爲mybatis-spring-boot-starter中已經包含了此依賴app
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> </dependencies>
spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
同其餘Spring Boot工程同樣,簡單且簡潔的的完成了基本配置,下面看看如何在這個基礎下輕鬆方便的使用MyBatis訪問數據庫。spring-boot
public class User { private Long id; private String name; private Integer age; // 省略getter和setter }
@Mapper public interface UserMapper { @Select("SELECT * FROM USER WHERE NAME = #{name}") User findByName(@Param("name") String name); @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age); }
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
建立單元測試單元測試
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) public class ApplicationTests { @Autowired private UserMapper userMapper; @Test @Rollback public void findByName() throws Exception { userMapper.insert("AAA", 20); User u = userMapper.findByName("AAA"); Assert.assertEquals(20, u.getAge().intValue()); } }