
在Springboot 项目中集成 mybatis。 官方介绍:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
Step:1 使用 IDEA 编辑器,点击 Create New Project, 选择 Spring Initializr

Setp-1
Step:2

Step:2
Step:3

Step:3
这里创建项目时应用了 4个类库:
Springboot 使用 application.propery 或者 application.yml 来配置应用。我这里用了 application.yml ,你可以创建一个。
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot_mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.example.entity
# 打印日志。比如你的包名在: cn.zyfvir.demo.mapper 下
logging:
level:
cn:
zyfvir:
demo : debugmybaits 支持两种方式映射:
实际项目中可以混合使用,我这里都做了示例。
先看下我的代码结构:

image.png
开始编写代码
写个实体类
public class City {
private Long id;
private String name;
private String state;
private String country;
}mapper 映射类
@Mapper
public interface CityMapper {
@Select("SELECT * FROM city WHERE status = #{status}")
City findByStatus(@Param("status") int status);
List<City> findAll();
}编写service类
public interface CityService {
City findByStatus(int status);
List<City> findAll();
}
/* 实现类 */
@Service
public class CityServiceImpl implements CityService {
@Autowired
CityMapper cityMapper;
@Override
public City findByStatus(int status) {
return cityMapper.findByStatus(status);
}
@Override
public List<City> findAll() {
return cityMapper.findAll();
}
}控制器类
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired
CityService cityService;
@RequestMapping("/findByStatus")
public City findByStatus(int status){
return cityService.findByStatus(status);
}
@RequestMapping("/findAll")
public List<City> findAll(){
return cityService.findAll();
}
}在浏览器打开这个地址: http://localhost:8080/city/findAll http://localhost:8080/city/findByStatus?status=1
我的建表语句:
CREATE TABLE city
(
id INT PRIMARY KEY auto_increment,
name VARCHAR(100) NULL,
status INT NOT NULL,
country VARCHAR(100) NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '城市';
INSERT INTO city (name,STATUS) VALUES ('北京',0);
INSERT INTO city (name,STATUS) VALUES ('上海',0);
INSERT INTO city (name,STATUS) VALUES ('河北',1);我的代码示例: https://github.com/vir56k/java_demo/tree/master/mybatisdemo8_springboot_mybatis
MyBatis Spring-Boot-Starter 将帮助你在 Spring Boot 中使用 MyBatis https://github.com/mybatis/spring-boot-starter
http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
https://github.com/mybatis/spring-boot-starter/wiki/Quick-Start