Mybatis初期使用比较麻烦,需要各种配置文件、实体类、dao层映射关联、还有一大推其它配置。当然Mybatis也发现了这种弊端,初期开发了generator可以根据表结构自动生成实体类、配置文件和dao层代码,可以减轻一部分开发量;后期也进行了大量的优化可以使用注解了,自动管理dao层和配置文件等,发展到最顶端就是今天要讲的这种模式,mybatis-spring-boot-starter就是springboot+mybatis完全注解不用任何配置文件,就可以简单配置轻松上手。

mybatis-spring-boot-starter主要有两种解决方案,一种是使用注解解决一切问题,一种是简化后的老传统。

以注解版的方式进行讲解。

users表结构

CREATE TABLE `users` (`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',`username` varchar(32) DEFAULT NULL COMMENT '用户名',`password` varchar(32) DEFAULT NULL COMMENT '密码',`sex` varchar(32) DEFAULT NULL,`nick_name` varchar(32) DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `username` (`username`) USING HASH
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;

1、添加pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.lynch.springboot</groupId><artifactId>spring-boot-mybatis-annotation</artifactId><version>0.0.1-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><!-- mybatis分页插件 --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.1.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

2、application.properties 添加相关配置

#mybatis.type-aliases-package=com.lynch.entityspring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://192.168.1.149:3306/aa?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username = root
spring.datasource.password = attack

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对于开发人员不用管,直接拿来使用即可。

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

package com.lynch;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.lynch.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个mapper加个注解也挺麻烦的。

3、开发Mapper

package com.lynch.mapper;import java.util.List;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;import com.lynch.entity.UserEntity;
import com.lynch.enums.SexEnum;public interface UserMapper {@Select("SELECT * FROM users")@Results({ @Result(property = "sex", column = "sex", javaType = SexEnum.class),@Result(property = "nickName", column = "nick_name") })List<UserEntity> getAll();@Select("SELECT * FROM users WHERE id = #{id}")@Results({ @Result(property = "sex", column = "sex", javaType = SexEnum.class),@Result(property = "nickName", column = "nick_name") })UserEntity getOne(Long id);@Insert("insert into users(username,password,sex) values(#{username}, #{password}, #{sex})")int insert(UserEntity user);@Update("UPDATE users SET userName=#{username},nick_name=#{nickName} WHERE id =#{id}")void update(UserEntity user);@Delete("DELETE FROM users WHERE id =#{id}")void delete(Long id);@InsertProvider(type=UserProvider.class, method = "batchInsert")int batchInsert(@Param("userList")List<UserEntity> userList);@SelectProvider(type = UserProvider.class, method = "queryUser")@Results({ @Result(property = "sex", column = "sex", javaType = SexEnum.class),@Result(property = "nickName", column = "nick_name") })public List<UserEntity> queryUser(UserEntity user);@UpdateProvider(type = UserProvider.class, method = "updateUser")public int updateUser(@Param("U")UserEntity user);
}

package com.lynch.mapper;import java.util.List;
import java.util.Map;import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;import com.github.pagehelper.util.StringUtil;
import com.lynch.entity.UserEntity;/*** 利用@Provider实现动态SQL* * @author Lynch**/
public class UserProvider {public String queryUser(UserEntity user) {StringBuffer sql = new StringBuffer("select * from users where 1=1 ");if(StringUtil.isNotEmpty(user.getUsername())) {sql.append(String.format("and username like '%s'", "%"+user.getUsername()+"%"));}return sql.toString();}public String batchInsert(Map map) {List<UserEntity> userList = (List<UserEntity>)map.get("userList");StringBuffer sql = new StringBuffer("insert into users (username,password) values ");for(UserEntity user : userList) {sql.append(String.format("('%s', '%s'),", user.getUsername(), user.getPassword()));}sql = sql.deleteCharAt(sql.length() -1);System.out.println(sql.toString());return sql.toString();}public String updateUser(@Param("U")UserEntity user) {SQL sql = new SQL(){{UPDATE("users");if (StringUtil.isNotEmpty(user.getNickName())){SET("nick_name = #{U.nickName}");}WHERE("id = #{U.id}");}};return sql.toString();}}

注意,使用#符号和$符号的不同:

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

4、单元测试

package com.lynch.mapper;import java.util.ArrayList;
import java.util.List;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import com.lynch.entity.UserEntity;
import com.lynch.enums.SexEnum;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void insert() throws Exception {int result = 0;try {result = userMapper.insert(new UserEntity("lisi", "123456", SexEnum.MAN));} catch (Exception e) {System.out.println(e.getMessage().indexOf("ConstraintViolationException"));}System.out.println("result=" + result);}@Testpublic void batchInsert() throws Exception {List<UserEntity> userList = new ArrayList<UserEntity>();userList.add(new UserEntity("a","a",SexEnum.MAN));userList.add(new UserEntity("c","b",SexEnum.MAN));userList.add(new UserEntity("b","b",SexEnum.WOMAN));System.out.println("result=" + userMapper.batchInsert(userList)); }@Testpublic void getAll() throws Exception {List<UserEntity> users = userMapper.getAll();System.out.println(users.toString());}@Testpublic void testUpdate() throws Exception {UserEntity user = userMapper.getOne(45L);System.out.println(user.toString());user.setNickName("neo");user.setSex(SexEnum.WOMAN);userMapper.update(user);}@Testpublic void queryUser() throws Exception {UserEntity user = new UserEntity();user.setUsername("l");System.out.println(userMapper.queryUser(user)); }@Testpublic void updateUser() throws Exception {UserEntity user = new UserEntity();user.setId(45L);user.setNickName("aaa");System.out.println(userMapper.updateUser(user)); }}

SpringBoot集成Mybatis(0配置注解版)相关推荐

  1. mybatis类型转换配置(springboot集成mybatis的配置)

    使用mybatis将string转为blob存入数据库时出现ora-01465异常,无效的十六进制转换!求解,求解 oracle中用于保存位串的数据类型是RAW,LONGRAW(推荐使用BLOB). ...

  2. 第 5 课 SpringBoot集成Mybatis(2)-配置文件版

    第五课 SpringBoot集成Mybatis(2)-配置文件版 文章目录 第五课 SpringBoot集成Mybatis(2)-配置文件版 1. 引入依赖:pom.xml 2. 配置applicat ...

  3. SpringBoot集成Mybatis项目实操

    本文为<从零打造项目>系列第三篇文章,首发于个人网站. <从零打造项目>系列文章 比MyBatis Generator更强大的代码生成器 SpringBoot项目基础设施搭建 ...

  4. springboot集成mybatis源码分析(一)

    springboot集成mybatis源码分析(一) 本篇文章只是简单接受使用,具体源码解析请看后续文章 1.新建springboot项目,并导入mybatis的pom配置 配置数据库驱动和mybat ...

  5. SpringBoot集成Mybatis用法笔记

    今天给大家整理SpringBoot集成Mybatis用法笔记.希望对大家能有所帮助! 搭建一个SpringBoot基础项目. 具体可以参考SpringBoot:搭建第一个Web程序 引入相关依赖 &l ...

  6. SpringBoot教程(十一) | SpringBoot集成Mybatis

    上一篇文章我们介绍了SpringBoot集成JdbcTemplate.简单体验了一下JdbcTemplate框架的用法,今天的内容比较重要,我们来介绍一下SpringBoot集成Mybatis的步骤. ...

  7. SpringBoot——SpringBoot集成MyBatis

    目录 1 SpringBoot集成MyBatis 1.1 准备工作 1.2 pom.xml文件 1.3 核心配置文件(application.properties) 1.4 GeneratorMapp ...

  8. SpringBoot集成MyBatis(iBatis)

    SpringBoot集成MyBatis(iBatis) 最近也是在写安卓的登陆注册作业,需要一个后台,这样方便点,开始用的是SpringMVC+Hibernate.但再搭建完之后发现配置啥的都挺多,于 ...

  9. springboot集成mybatis原理剖析

    前言:本文主要基于springboot项目,从springboot的拓展角度来分析mybatis是如何与springboot集成的. 1.首先搭建springboot集成mybatis环境 1.1.m ...

最新文章

  1. Radware负载均衡项目配置实战解析之四-VRRP双机配置与同步
  2. Django Rest Framework之用户频率/访问次数限制
  3. 设计模式之Composite
  4. linux内核之 phys_to_virt
  5. G - 变形课 HDU - 1181(搜索之dfs)
  6. input 输入值的监听 禁止输入特殊字符
  7. usb接口供电不足_AMD RX 6000 系列显卡配备USB-C 接口,支持外接供电
  8. 《计算机算法设计与分析》题目汇总
  9. hadoop--HDFS搭建客户端API环境
  10. 2018春招-赛码网-例题-不确定输入组数的多组数列求和
  11. jQuery源码高清视频教程
  12. linux 小度wifi,树莓派2小度wifi(MT7601U)驱动
  13. 可调电阻封装图_看过来!!国产大神把ZXD2400 v4.3完美改造成60V50A可调数控电源...
  14. 免费的端口映射工具哪个好用
  15. 生物信息分析员的编程小站
  16. 最新elasticsearch版本与jdk版本对应图
  17. Python:摄氏温度转华氏温度
  18. 基于环信的开源即时通讯项目
  19. 彻底搞懂CNN中的卷积和反卷积
  20. 你在日常的测试工作中遇到过哪些困境呢?

热门文章

  1. jstl java_JSTL-Java-Baby-51CTO博客
  2. insert 语句_CTF从入门到提升(七)insert 等数据表相关操作注入及例题分享
  3. 文件共享服务器连接数问题,共享服务器上连接数量的设置
  4. kafka linux客户端,kafka linux 客户端操作命令
  5. oracle每一行的hash值,Hash分区表分区数与数据分布的测试
  6. php正则表达式实例详解,正则表达式实例解析
  7. 如果服务器开机显示NObootable,电脑不能开机提示No bootable device怎么办?
  8. 电子白板技术_电子白板种类介绍及产品功能概述
  9. maya导入abc动画_三维文件格式知多少 | abc、glTF、fbx、obj、dae、stl、3ds...
  10. python字典新的定义方式