Spring Boot版本:2.0.6.RELEASE。
源代码:https://github.com/wu-boy/parker.git parker-mybatis模块
SpringBoot2集成MyBatis可以通过引入mybatis-spring-boot-starter来实现。mybatis-spring-boot-starter主要有两种解决方案,一种是使用注解解决一切问题,一种是简化后的老传统,本人倾向于使用后者。
项目架构可以直接看源代码,这里捡主要内容说。
application.yml配置如下
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://127.0.0.1:5432/test
username: postgres
password: postgres
mybatis:
type-aliases-package: com.wu.parker.mybatis
mapper-locations: classpath:mybatis/*.xml
configuration:
cache-enabled: true
auto-mapping-behavior: FULL
default-executor-type: REUSE
map-underscore-to-camel-case: true
lazy-loading-enabled: true
aggressive-lazy-loading: false
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
新建Mapper
package com.wu.parker.mybatis.dao;
import com.wu.parker.mybatis.po.User;
import org.apache.ibatis.annotations.Mapper;
/**
* @author: wusq
* @date: 2018/11/26
*/
@Mapper
public interface UserMapper {
int save(User user);
}
新建UserMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wu.parker.mybatis.dao.UserMapper">
<insert id="save" parameterType="user">
insert into user_test(id,username,password)values(#{id},#{username},#{password})
</insert>
</mapper>
Mapper接口里的方法名称和xml里的id要对应起来。
测试类
package com.wu.parker.mybatis.test;
import com.wu.parker.mybatis.dao.UserMapper;
import com.wu.parker.mybatis.po.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author: wusq
* @date: 2018/11/26
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void contextLoads() {
}
@Test
public void testSave() throws Exception {
User user = new User();
user.setId("1");
user.setUsername("admin");
user.setPassword("admin");
System.out.println(userMapper.save(user));
}
}
参考资料:
1、springboot(六):如何优雅的使用mybatis
2、XML映射配置文件