1、第一步:引入依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
2、application.yml
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://62.234.155.68:3306/account?characterEncoding=utf8&serverTimezone=UTC username: root password: ****** mybatis: type-aliases-package: com.example.springboot_allblue.bean mapper-locations: classpath:mapper/*Mapper.xml
此处要注意 username和password不是data-username和data-password,写错了,查询时提示连接不上数据库,调试了两个多小时才找到,血泪的教训
3、依次创建bean、mapper、service、controller代码包
注意:启动类上需加上 @MapperScan("mapper包路径")
mapper接口类上的注解为@mapper
4、在resource路径下创建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.example.springboot_allblue.mapper.UserMapper"> <resultMap id="userMap" type="User"> <id column="id" property="id"/> <result column="user_name" property="userName"/> </resultMap> <select id="selectAll" resultMap="userMap"> select * from my_user </select> </mapper>