018 mybatis的整合

一 . 概述

  在当前的jee之中,我们最常用的就是使用mybatis作为数据持久层的解决方案了.本次我们将mybatis整合到springboot之中.


二 . 整合的的基本步骤

(1)加入mybatis的依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

上面的这个启动器是由mybatis官方提供的,我们需要注意.

(2) 定义mapper接口,进行扫描的方式选择

  [1] 在接口之上加上一个@Mapper注解,那么这个接口就是一个Mapper注解了

  [2]使用@MapperScan() 进行批量的接口扫描

(3)配置我们的mybatis的sql文件的位置 

mybatis.mapper-locations=classpath:mapper/**/*.mapper.xml    

同时我们还可以配置如全局配置文件等.

下面简单的演示一个例子:  

<mapper namespace="com.trek.mapper.UserMapper">
    <select id="selectById" resultType="com.trek.bean.User">
        select * from user where id = #{id}
    </select>
</mapper>
@Mapper
public interface UserMapper {
    
    User selectById(Integer id);
}
@RestController
public class UserController {
    
    @Autowired
    private UserMapper userMapper;
    
    @GetMapping("/user/{id}")
    public User selectById(@PathVariable("id") Integer id) {
        return userMapper.selectById(id);
    }
}

我们主要是展示mybatis在springboot之中是怎么使用的.我们发现和之前的使用是没有什么变化的.仅仅就是配置变得简单了很多了而已.

猜你喜欢

转载自www.cnblogs.com/trekxu/p/9175554.html