SpringBoot整合MyBatis

SpringBoot整合MyBatis

MyBatis以其小巧灵活的特性,已经被很多互联网公司用于日常开发中。随着SpringBoot的流行,MyBatis同样也出了整合SpringBoot的方案。本篇文章简要介绍一下在SpringBoot中如何快捷的使用MyBatis。

依赖

首先是国际惯例、导入依赖包。绝大部分的框架或者工具都是通过一个boot-starter的依赖包。MyBatis也不例外。

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId> 
	<version>${mybatis.version}</version> 
</dependency>

配置

在SpringBoot中,基本上所有的配置都被划分为配置类和yaml(或properties)2部分。

以下列举一下必要配置,一些其它配置如驼峰和下划线的自动转换或者一些插件使用到的时候都可以查得到。

  1. yml
spring: 
	datasource: 
	url: jdbc:mysql://localhost:3306/dbName?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true 
	username: root 
	password: 123456 
	driver-class-name: com.mysql.cj.jdbc.Driver
  1. 配置类

在不注入插件的情况下,不需要单独写一个配置类,只需要在启动类上使用@MapperScan注解,其传递一个表示mapper所在包路径的成员。

这个注解实际上是对每个Mapper类上@Mapper的简化。是包扫描配置的注解版。

以上的配置完毕后,就可以进行持久层代码的编写了

Mapper的开发

Mapper是用来生产SQL的,生产的方式有2种。

  1. 注解方式

通过注解的方式可以省去mapper.xml,不过也很明显,发杂的SQL很难去实现,尤其是动态SQL。所以这种方式常用于简单的逻辑。

常用注解有五个:

  • @Select
@Select("select * from user")
List<User> findAll();
  • @Update
@Update("update user set name = #{name} where id = #{id}")
Integer updateNameById(@Param("name") String name,@Param("id") Lond id);
  • @Insert
@Insert("insert into user (name,age) values('zhangsan',23)")
Integer insertUser(@Param('name') String name,@Param('age') int age);
  • @Delete
@Delete("delete from user where id = #{id}")
Integer deleteById(Lond id);
  • @Reaults

定义需要返回的字段并映射到实体类中的字段中,一般还会有一个@Result和它配合使用

@Select("select * from user where id = #{id}")
@Results({
    @Result(property = "username",column = "username")
    @Result(property = "nickName",column = "nick_name")
})
User findOneById(Long id);
  1. xml方式

SpringBoot中的xml定义SQL和在Spring中一样使用。

本篇主要讲整合,具体的XML方式以及注解的复杂用法会另行在Mybatis的使用中介绍。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值