1、pom文件添加依赖
<!--mybatis依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency>
2、application.yml配置
#配置端口号 server: port: 8085 #数据库配置 spring: datasource: url: jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC username: root password: 123456 application: name: user #表名 #整合mybatis mybatis: configuration: map-underscore-to-camel-case: true #开启驼峰命名 type-aliases-package: com.donleo.mybatis.model #扫描包 mapper-locations: classpath:mappers/*.xml #mapper映射地址 #打印日志 logging: level: com.donleo.mybatis.dao: debug #打印看sql语句 #1、yml基本语法 # k:(空格)v:表示一对键值对(空格必须有) ; # 以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的 # # 属性和值也是大小写敏感; #2、值的写法 # 1)字面量、普通的值(数字、字符串、布尔) # k:v:字面直接来写; # 字符串默认不用加上单引号或者双引号; # # :双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思 # name:"zhangsan lisi" :输出; zhangsan换行lisi # # :单引号;会转义特殊字符,特殊字符最终只是-一个普通的字符串数据 # name: 'zhangsan In lis' :输出; zhangsan |lisi # 2)对象、Map(属性和值)(键值对) # k:v:在下- -行来写对象的属性和值的关系;注意缩进 # 对象还是k: v的方式 # friends: # lastName: zhangsan # age: 20 # 行内写法: # friends: {lastNane: zhangsan,age: 18} # 3)数组(List、Set) # 用-值表示数组中的一个元素 # pets: # -cat # -dog # -pig # 行内写法: # pets:[cat,dog,pig]
3、建实体
@Data @Builder @NoArgsConstructor @AllArgsConstructor public class Role implements Serializable { private Integer id; private String roleName; private String roleCode; private String introduce; }
4、mapper层
public interface IRoleMapper { }
5、在resource下新建mappers文件夹,添加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.donleo.mybatis.dao.IRoleMapper"> <resultMap id="BaseResultMap" type="com.donleo.mybatis.model.Role"> <id column="id" jdbcType="INTEGER" property="id"/> <result column="role_name" jdbcType="VARCHAR" property="roleName"/> <result column="role_code" jdbcType="VARCHAR" property="roleCode"/> <result column="introduce" jdbcType="VARCHAR" property="introduce"/> </resultMap> <sql id="Base_Column_List"> id, role_name, role_code, introduce </sql> </mapper>
6、启动类
添加@MapperScan扫描mapper层接口
@SpringBootApplication @MapperScan("com.donleo.mybatis.dao") public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } }