步骤

1、在pom.xml导入依赖

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

2、配置配置文件

spring:
  datasource:
    username: root
    password: awei0129..
    url: jdbc:mysql://localhost:3306/java_mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

#整合Mybatis
mybatis:
  type-aliases-package: com.awei.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml
server:
  port: 8081

3、测试数据库是否连接成功

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() {
        System.out.println(dataSource.getClass());
    }

4、编写Mapper接口

@Mapper
@Repository
public interface UserMapper {
    List<User> queryUserList();
}

5、编写SQL resource/mybatis/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.awei.mapper.UserMapper">

    <select id="queryUserList" resultType="User">
        select * from user;
    </select>

</mapper>

6、编写Controller测试

@RestController
public class UserController {
    
    @Autowired
    private UserMapper userMapper;
    
    @GetMapping("/getUserList")
    public List<User> userList(){
        List<User> users = userMapper.queryUserList();
        return users;
    }
    
}

7、查看结果
结果

结果输出没问题,测试完毕。

最后修改:2021 年 03 月 04 日 09 : 21 AM
要饭啦!!!赞赏一点吧!!!