前面已经创建数据表和JAVABEAN,如何用mybatis来对数据进行增删改查,我们先说mybatis注解版的使用,我来写上一个mapper,操作我们这个数据库,我们放在mapper包下,我们操作department表的,Mybatis我们只需要一个interface,来写一个接口就行了,首先要用一个注解,@Mapper,注解来告诉mybatis,指定这是一个操作数据库的一个mapper就行了,那接下来我们就来定义方法,我们来查出一个部门,我们按照一个id来查一个部门,我们可以直接把SQL语句写在方法上,增删改查我们用注解的方式写上来了,我们来写一个Controller来测一测
package com.learn.mapper;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import com.learn.entities.Department;// 指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")public Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")public int deleteDeptById(Integer id);@Options(useGeneratedKeys=true,keyProperty="id")@Insert("insert into department(deptName) values(#{deptName})")public int insertDept(Department department);@Update("update department set deptName=#{deptName} where id=#{id}")public int updateDept(Department department);}
CREATE TABLE `department` (`id` int(11) NOT NULL AUTO_INCREMENT,`deptName` varchar(20) DEFAULT NULL,`principal` varchar(20) DEFAULT NULL,`functional` varchar(50) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
我们就叫DeptController,我就直接写一个@RestController,不返回页面,直接返回JSON数据,我们先返回一个department,我们使用mapper查询就行了,我们不写service层了,id以请求参数的方式传过来,带上部门id,我们用占位符的方式,@PathVariable路径变量,我们以占位符的方式取出id,查出这个内容,让他返回数据,包括再来插入一条数据,插入还是返回department,我们把所有的数据封装成Department对象,我们来测试一下能不能进行工作http://localhost:8080/dept/1
package com.learn.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;import com.learn.entities.Department;
import com.learn.mapper.DepartmentMapper;@RestController
public class DeptController {@AutowiredDepartmentMapper departmentMapper;@GetMapping("/dept/{id}")public Department getDepartment(@PathVariable("id") Integer id) {return departmentMapper.getDeptById(id);}@GetMapping("/dept")public Department insertDept(Department department) {departmentMapper.insertDept(department);return department;}}
http://localhost:8080/dept?deptName=AA{"id":4,"deptName":"AA","principal":null,"functional":null}我们发现他确实插入进去了,如果想用Mybatis,想用注解版就非常简单,只需要写一个mapper,Mapper注解加进来就行,注解版的使用,我们不需要做任何配置,我们来搜索MybatisAutoConfiguration,包括SqlSessionFactory要用的各种属性,MybatisProperties有各种前缀,前缀就是mybatispublic static final String MYBATIS_PREFIX = "mybatis";但是注解版什么都不用配置,我们再来插入一个BB,发现没有部门id,我们想要获取到自增id,我们可以在insert上给他设置一下,@Options(useGeneratedKeys=true,keyProperty="id")
@Insert("insert into department(deptName) values(#{deptName})")
public int insertDept(Department department);@Options里面有一个属性,就和我们以前写xml一样,useGeneratedKeys,是不是使用自动生成的主键,写一个true,包括告诉人家,哪个属性是封装主键的,我们用keyProperty,Department中的id属性是用来封装主键的,当插入以后主键会自动封装进来,我们Controller会再次用到department,就有主键了,是不是我们插入的东西就能获取到主键呢,发现自增主键就有了,那我们再来查询一下,查询也是没问题的,这就是我们使用注解版,在不做任何配置的情况下,我们就写我们的mapper就行了,没什么问题,但是我们再来考虑一个小问题,给我们容器创建SqlSessionFactory的时候,有一个configuration,就是我们配置的相关配置,@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
Configuration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {configuration = new Configuration();
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {for (ConfigurationCustomizer customizer : this.configurationCustomizers) {customizer.customize(configuration);}
}
factory.setConfiguration(configuration);
if (this.properties.getConfigurationProperties() != null) {factory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
if (!ObjectUtils.isEmpty(this.interceptors)) {factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {factory.setMapperLocations(this.properties.resolveMapperLocations());
}return factory.getObject();
}而这个相关的配置呢,这一块还有一个ConfigurationCustomizer,就是来帮我们定制的,那我们想要改我们mybatis的相关规则,MyBatisConfig,我们也给容器中加一个ConfigurationCustomizer,这是一个接口,我们就直接来new一个ConfigurationCustomizer,没有实现的方法就在内部类里面来实现,有一个setMapUnderscoreToCamelCase,驼峰命名发规则,这个要起作用,我们要把它return,而且还要加载容器中,我们把它@Bean,加在容器中,我们把这个配置类@org.springframework.context.annotation.Configuration,来告诉他这个是一个配置类,接下来我们来看这个配置类能不能生效
package com.learn.config;import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;@org.springframework.context.annotation.Configuration
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer() {return new ConfigurationCustomizer() {@Overridepublic void customize(Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true);}           };}
}
这个注解用的是全类名,由于Mybatis的Configuration已经导进来了,你就启动一下,看我们自定义的驼峰命名规则能不能起作用,我们发现数据就查出来了,我们可以使用这种方式,来自定义mybatis的配置规则,我们就叫自定义mybatis的配置规则,只要把它自定义配置的源码,大概瞅一瞅就知道该怎么做了,给容器中添加一个ConfigurationCustomizer组件就行了,跟我们以前Customer一样,另外我们再来扩展一下,如果我们Mapper特别多的情况下,我们给每一个Mapper上标注Mapper注解,如果不标记Mapper注解,肯定是没用的,Mapper就找不到了,就直接报错了,自动装配就会有问题,所以Mapper注解不可少,但是我们后来的Mapper非常多,每一个类上都来加Mapper,太麻烦了,我们来加上一个注解,叫做@MapperScan@MapperScan(value="com.learn.mapper")这里我们可以指定一个basePackages,/**
* Base packages to scan for MyBatis interfaces. Note that only interfaces
* with at least one method will be registered; concrete classes will be
* ignored.
*/
String[] basePackages() default {};写value值也是一样的,我们就来指定com.learn.mapper,mapper下的类相当于都加上了Mapper注解,我来重新启动,我们这个能不能使用呢,我们启动的时候不会报错,然后我们在这查询http://localhost:8080/dept/2也能查出来{"id":2,"deptName":"实施部","principal":"张经理","functional":"负责公司软件维护工作"}
package com.learn.mapper;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import com.learn.entities.Department;// 指定这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")public Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")public int deleteDeptById(Integer id);@Options(useGeneratedKeys=true,keyProperty="id")@Insert("insert into department(deptName) values(#{deptName})")public int insertDept(Department department);@Update("update department set deptName=#{deptName} where id=#{id}")public int updateDept(Department department);}
package com.learn;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** @SpringBootApplication 来标注一个主程序类,说明这是一个Sprint Boot应用* @author Leon.Sun**/
//@ImportResource(locations= {"classpath:beans.xml"})
@MapperScan(value="com.learn.mapper")
@SpringBootApplication
public class SpringBoot02ConfigApplication {public static void main(String[] args) {// Spring应用启动起来SpringApplication.run(SpringBoot02ConfigApplication.class,args);}}
可以使用MapperScan批量扫描,所有的Mapper接口,这就是我们使用的注解版的mybatis,非常简单,只需要写一个mapper就行了,如果想自定义,写一个Customer,如果想要批量扫描就用@MapperScan

SpringBoot_数据访问-整合MyBatis(二)-注解版MyBatis相关推荐

  1. SpringBoot_数据访问-整合MyBatis(二)-配置版MyBatis

    前面使用全注解的方式,我们写了一个Mybatis的类,我们对数据库进行增删改查的操作,在实际开发中呢,我们也经常使用配置文件的方式,我们需要一个Mybatis的全局配置文件,包括写一个映射文件,那我们 ...

  2. SpringBoot_数据访问-整合MyBatis(一)-基础环境搭建

    前面整合了基本的JDBC,也配置了druid数据源,那接下来就整合mybatis,整合mybatis呢,数据访问使用的是mybatis,那mybatis要怎么用呢,下一步选择我们需要的模块,先把web ...

  3. SpringBoot_数据访问-整合Druid配置数据源监控

    然后实际在开发的时候,我们很少用到这个数据源,比如我们用c3p0,或者开发常用的druid,这是我们阿里的数据源产品,虽然Hikarui的性能比druid要好一点,由于druid有安全监控的整个解决方 ...

  4. Spring Boot 实战 —— MyBatis(注解版)使用方法

    原文链接: Spring Boot 实战 -- MyBatis(注解版)使用方法 简介 MyBatis 官网 是这么介绍它自己的: MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过 ...

  5. SpringBoot_数据访问-JDBC自动配置原理

    整合最基本的JDBC和数据源,第一个MYSQL,导入mysql驱动的,第二个我们使用原生的JDBC,后面使用Mybatis和JPA再选相应的内容就行了,为了演示方便我也把WEB模块选中,我们在pom文 ...

  6. SpringBoot_数据访问-简介

    SpringBoot与数据访问,SpringBoot如何与关系型数据进行交互,我们将会使用JDBC技术,包括持久层框架Mybatis,以及Spring Data JPA,这三个都是和关系型数据库进行交 ...

  7. 打造自己的数据访问层(二)

    上一篇打造自己的数据访问层(一)中,我们已了解了.NET对数据库操作的基本原理,并就Ado.net对象的使用提出了几点疑问: 1.如何由系统来判断数据库型. 2.如何消除这些重复代码. 而上篇中也提出 ...

  8. idata 数据访问组件库 (2021版)

    idata数据访问组件库(RX11)版本:  2022-09-20 下载: idata 数据组件库 for RAD Studio RX10.3.x (260) 发布于:2020-02-20    使用 ...

  9. 七十一、Springboot整合MyBatis(注解版)

    @Author:Runsen 来源:尚硅谷 下面建议读者学习尚硅谷的B站的SpringBoot视频,我是学雷丰阳视频入门的. 具体链接如下:B站尚硅谷SpringBoot教程 文章目录 创建Sprin ...

最新文章

  1. linux下多线程的调试
  2. (转)ThreadPoolExecutor最佳实践--如何选择队列
  3. day3-python学习笔记(二)list(数组)
  4. Hyperledger Fabric 1.0 从零开始(十二)——fabric-sdk-java应用【补充】
  5. 每日算法系列【LeetCode 面试题 17.05】字母与数字
  6. Ubuntu 下使用apt-get安装最新版本的MySQL
  7. Delphi之TStrings和TStringLists类【转】
  8. 通过谷歌浏览器,找到页面某个事件属于哪个js文件
  9. 第一方数据,第二方数据,第三方数据:你了解多少?
  10. unity -- 存档与读档
  11. windows PC/SC 常用Scard前缀函数说明
  12. 为什么有时优盘是只读模式_u盘怎么解除只读模式
  13. 【VK】商品多规格SKU选择器组件豪华版(uniapp版,可编译成H5、APP、各大小程序)
  14. 纯干货分享,新手小白如何精细化运营,玩转抖音小店无货源店群?
  15. Microsoft Bitlocker企业级管理部署方案
  16. Less or Equal
  17. vue之实现移动端的复制粘贴功能(两种写法)
  18. UDK 中的委托使用
  19. Tomcat启动项目警告: org.apache.jasper.servlet.TldScanner.scanJars 至少有一个JAR被扫描用于TLD但尚未包含TLD
  20. DeFi聚合层的价值可能被低估了 |链捕手

热门文章

  1. ExtJS 中自定义类
  2. Window 7 下的某些服务不能随便禁用! 无法立即删除.exe文件,因为禁用了Application Experience服务。...
  3. Bat命令:从Ftp获取文件以及数据导入
  4. 快速了解Python并发编程的工程实现(下)
  5. javaScript变量、作用域链
  6. Android Studio 3.3 Beta提供了新的Android代码压缩器R8
  7. RabbitMQ远程不能访问问题的解决
  8. mysqlsla日志分析工具
  9. Execl导入问题之文本转换
  10. 谷歌发布“虚拟现实化”游戏 Ingress