SpringBoot2.0学习之集成mybatis
1. 在pom.xml中引入mybatis和mysql的依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
2. application.yml中添加数据库连接的配置
### mybatis配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/marklife?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root123
3. 测试,代码如下:
mapper:
public interface UserMapper {
@Insert("insert into t_user(name, age) values(#{name},#{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
service:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int insert(String name, Integer age) {
return userMapper.insert(name, age);
}
}
controller:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/insert")
public String insert(String name, Integer age){
userService.insert(name, age);
return "success";
}
}
注意:添加扫包注解
需要在Mapper上添加@Mapper注解
或者在启动类上添加@MapperScan注解
两种选一种,建议第二种,第一种太麻烦而且容易忘记。
测试结果: