我真菜
被Spring整合MyBatis打击到了,所以转向Spring Boot
我太菜了!!!
事先准备
一个User对象
1 | //lombok插件简单粗暴 |
2 | public class User { |
3 | private int userId; |
4 | private String username; |
5 | private String password; |
6 | } |
一张User表

字段名和属性名对应
接口处理
1 | public interface IUserMapper { |
2 | String getFirst(); |
3 | User getById(int id); |
4 | } |
启动类上开启扫描
1 | ("com.czw.springbootmybatis.mapper") |
XML文件编写SQL语句并映射到接口(mapper标签的namespace)且对应接口方法名(id)
1 | <?xml version="1.0" encoding="UTF-8" ?> |
2 | <!DOCTYPE mapper |
3 | PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" |
4 | "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
5 | <mapper namespace="com.czw.springbootmybatis.mapper.IUserMapper"> |
6 | <select id="getFirst" resultType="String"> |
7 | select username from user where user_id = 1 |
8 | </select> |
9 | <select id="getById" resultType="com.czw.springbootmybatis.bean.User"> |
10 | select * from user where user_id = #{userId} |
11 | </select> |
12 | </mapper> |
配置文件
1 | #数据源配置 |
2 | =root |
3 | =root |
4 | =jdbc:mysql://localhost:3306/learningssm?serverTimezone=UTC |
5 | #映射xml文件并实现下划线和大写转化 |
6 | =classpath:mapper/*.xml |
7 | =true |
业务层
1 | //存入IoC容器 |
2 | public class UserService { |
3 | |
4 | private IUserMapper userMapper; |
5 | //自动注入 |
6 | public String getFirst(){ |
7 | return userMapper.getFirst(); |
8 | } |
9 | //调用方法 |
10 | public User getById(int id) { |
11 | return userMapper.getById(id); |
12 | } |
13 | } |
测试
1 | |
2 | UserService userService; |
3 | //注入Service |
4 | |
5 | void contextLoads() { |
6 | String str=userService.getFirst(); |
7 | System.out.println(str); |
8 | User user=userService.getById(1); |
9 | System.out.println(user.toString()); |
10 | } |
结果
可想而知

总结
头发-0,舒服了,Spring Boot真好