SpringBoot整合mybatis

一、引入依赖

<dependencies>
<!-- 核心启动器, 包括auto-configuration、logging and YAML -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 数据库操作需要的mysql 驱动包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>
<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>

二、application.properties

#这里要注意&,可能在spring的xml中我们用的是转义符号(&amp;),但是在这里不用
spring.datasource.url=jdbc:mysql://192.168.178.5:12345/mydb?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource

####### mybatis #######
# 指定映射文件的具體位置
mybatis.mapper-locations=classpath:mapper/*.xml

三、创建Mapper接口

/**
 * @Mapper 用于扫描Mapper接口,生成代理对象, 也可以在启动类使用@MapperScan(basePackages = {包名})声明
 * 但一定要注意@Repository是不能少的, 否则在其他地方注入时不能识别
 */
@Mapper
@Repository
public interface UserMapper {
    List<Map<String,Object>> listUsers();
}

四、创建Mapper映射文件

位置与application.properties的mybatis.mapper-locations保持一致,在resources下创建mapper目录,在该目录下创建UserMapper.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.mybatis.modules.user.mapper.UserMapper">
    <!-- 查询所有用户 -->
    <select id="listUsers" resultType="java.util.HashMap">
        select * from user
    </select>
</mapper>

五、单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MybatisApplication.class})
class MybatisApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        List<Map<String, Object>> userList = userMapper.listUsers();
        if(userList != null && userList.size()>0){
            for(Map<String,Object> user : userList){
                System.out.println("id:" + user.get("id"));
                System.out.println("username:" + user.get("name"));
                System.out.println("age:" + user.get("age"));
            }
        }
    }
}

相关推荐