🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 一.添加Mybatis的起步依赖 在`pom.xml`文件中加入 ~~~ <!-- mybatis起步依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> ~~~ ***** ### 二.添加数据库驱动坐标 ~~~ <!-- MySQL连接驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ~~~ ***** ### 三.添加数据库连接信息 ~~~ #数据库连接信息 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC username: root password: admin123 ~~~ ***** ### 四.创建user表 ~~~ package com.youworker.domain; import lombok.Data; /** * @author: youge * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-01-05 17:19 */ @Data public class User { private Integer id; private String username; private String password; } ~~~ ***** ### 五.创建实例Bean ***** ### 六.编写Mapper ~~~ package com.youworker.mapper; import com.youworker.domain.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @author: youge * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-01-05 17:30 */ @Mapper public interface UserMapper { public List<User> queryUserList(); } ~~~ ***** ### 七.创建Mapper映射文件 ~~~ <?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.youworker.mapper.UserMapper"> <select id="queryUserList" resultType="User"> select * from user </select> </mapper> ~~~ ***** ### 八.在application.yml中添加mybatis配置 ~~~ #配置 mybatis 的信息 mybatis: type-aliases-package: com.youworker.domain mapper-locations: classpath:mapper/*Mapper.xml ~~~ ***** ### 九.编写测试Controller ~~~ package com.youworker.controller; import com.youworker.domain.User; import com.youworker.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author: youge * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-01-05 17:40 */ @RestController public class MybatisController { @Autowired private UserMapper userMapper; @GetMapping("/queryUserList") public List<User> queryUserList(){ List<User> users = userMapper.queryUserList(); return users; } } ~~~ ***** ### 十.测试