**
SpringBoot整合Mybatis
**
Step1:pom导入
<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>
<!-- mybaties -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Step2:数据库配置文件
1、Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ykd.mapper.UserMapper" >
<insert id="save">
insert into user (username,password) VALUES(#{0},#{1})
</insert>
<select id="findByUsername" resultType="com.ykd.model.User" parameterType="string">
select * from user where username = #{username,jdbcType=VARCHAR}
</select>
</mapper>
注意这里需要在pom中添加下面代码
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
step3:Controller
@RestController //声明Rest风格的控制器
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 通过姓名查找用户信息
* @param name
* @return
*/
@RequestMapping("find")
@ResponseBody //响应体,自动返回json格式数据
public User find(String name){
return userService.findByName(name);
}
/**
* 创建一个新的用户
* @param name
*/
@ResponseBody
@RequestMapping("/add")
public int add(String name) {
return userService.insert(name,"123");
}
}
Step4:App
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.ykd") //扫描controller层和servce层
@MapperScan(value="com.ykd.mapper") //扫描mapper层
public class App
{
public static void main(String[] args) {
//启动springboot项目
SpringApplication.run(App.class,args);
}
}