SpringBoot (四) :优雅的使用 mybatis

由于项目中使用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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,958评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,948评论 18 139
  • 这两天启动了一个新项目因为项目组成员一直都使用的是mybatis,虽然个人比较喜欢jpa这种极简的模式,但是为了项...
    极乐君阅读 1,356评论 2 26
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 1,001评论 0 2
  • 勇者不惧,智者不惑 ——记薪火传承工程主讲周士忠老师 10月9日晚,我校薪火传承工程进行时!本次活动由我校周士忠老...
    煜苅千歌阅读 467评论 0 0