美文网首页Springboot
SpringBoot (四) :优雅的使用 mybatis

SpringBoot (四) :优雅的使用 mybatis

作者: 阿亮私语 | 来源:发表于2017-08-15 21:44 被阅读116次

由于项目中使用mybatis比较多,并且mybatis这种半orm形式的持久层框简单又不失可控性,所以这一章简单讲一下springboot与mybatis的集成。

mybatis-spring-boot-starter

官方说明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
Springboot整合mybatis主要有两种方案,一种是使用注解解决,另一种是简化后的传统方式。
当然两种方式首先都得添加pom依赖,这是必不可少的

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

无配置文件注解

即所有问题都通过注解解决,这也是我喜欢的方式

1、添加pom文件

<!-- mybatis相关-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

2、application.properties 添加相关配置

mybatis.mapperLocations=classpath*:/mapper/*.xml

在启动类中添加对mapper包扫描@MapperScan。

@MapperScan(basePackages = {"com.liangliang.lessons.mapper"})
@SpringBootApplication
public class LessonsApplication {

    public static void main(String[] args) {
        SpringApplication.run(LessonsApplication.class, args);
    }
}

3、开发mapper

@Mapper
public interface UserMapper {
    List<UserEntity> getAll();

    UserEntity getOne(Long id);

    void insert(UserEntity user);

    void update(UserEntity user);

    void delete(Long id);
}

为了更接近生产我特地将user_sex、nick_name两个属性在数据库加了下划线和实体类属性名不一致,另外user_sex使用了枚举。

4、使用

上面三步就基本完成了相关dao层开发,使用的时候当作普通的类注入进入就可以了。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserMapperTest {
    @Autowired
    UserMapper userMapper;
    @Test
    public void getAll() throws Exception {
        System.out.println("----------userMapper:"+userMapper);
        userMapper.getOne(1l);
    }

    @Test
    public void getOne() throws Exception {
    }

    @Test
    public void insert() throws Exception {
    }

    @Test
    public void update() throws Exception {
    }

    @Test
    public void delete() throws Exception {
    }

}

到此,单元测试完成,controller中写法在代码中有详细的注解,直接使用即可,对于另一种在mapper中写sql注解的方式,这里不做说明,这种做法对代码侵入性太高,不建议使用,网上也有相应教程,感兴趣的小伙伴可以自行写。
同样代码地址在
https://github.com/liangliang1259/daily-lessons.git 中的项目lessons-4

相关文章

网友评论

    本文标题:SpringBoot (四) :优雅的使用 mybatis

    本文链接:https://www.haomeiwen.com/subject/hwtbrxtx.html