1、SpringBoot整合MyBatis

1.1 application.yml

# 数据源配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/kh96_ssm_airms?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username: root
password: root # mybatis 核心配置
mybatis:
configuration:
map-underscore-to-camel-case: true # 下划线 映射 驼峰
mapper-locations: classpath:mybatis/mapper/*.xml # 自定义mapper映射路径
# config-location: classpath:mybatis-config.xml # mysql配置文件

1.2 实体类

@Data
public class Quality { //编号
private Integer id; //地区id
private Integer did; //检测时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone =" GMT+8")
private Date monitorTime; //pm10
private Integer pm10; //pm25
private Integer pm25; //监测站
private String monitorStation; //修改时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone =" GMT+8")
private Date lastModifyTime; }

1.3 mapper 和 service

1.3.1 QualityMapper

public interface QualityMapper {

    //根据空气质量编号,修改空质量
Integer updateQualityById(Quality qualityForm); }

1.3.2 QualityMapper.xml

<!--
根据空气质量编号,修改空质量
Integer updateQualityById(Quality qualityForm);
-->
<update id="updateQualityById">
update air_quality
<set>
<if test="id != null"> `id` = #{id},</if>
<if test="did != null"> `did` = #{did},</if>
<if test="monitorTime != null"> `monitor_time` = #{monitorTime},</if>
<if test="pm10 != null"> `pm10` = #{pm10},</if>
<if test="pm25 != null"> `pm25` = #{pm25},</if>
<if test="monitorStation != null"> `monitor_station` = #{monitorStation},</if>
<if test="lastModifyTime != null"> `last_modify_time` = #{lastModifyTime},</if>
</set>
where `id` = #{id}
</update>

1.3.3 service

//接口
public interface QualityService {
boolean modifyQualityById(Quality qualityForm);
} //实现类
@Service
public class QualityServiceImpl implements QualityService { @Autowired
private QualityMapper qualityMapper; @Override
public boolean modifyQualityById(Quality qualityForm) {
return qualityMapper.updateQualityById(qualityForm) > 0;
}
}

1.4 测试

1.4.1 控制层

@Slf4j
@RestController
public class AirQualityController { @Autowired
private QualityService qualityService; //根据空气质量编号,修改空质量,使用xml映射文件
@PostMapping("/modQuality")
public Map<String,String> testModifyQualityMapperXml(@RequestBody Quality qualityForm){ //返回集合
Map<String,String> returnMap = new HashMap<>(); //调用业务接口,修改空气详情
if(qualityService.modifyQualityById(qualityForm)){
returnMap.put("code","200");
returnMap.put("msg","Success"); return returnMap;
} returnMap.put("code","9999");
returnMap.put("msg","Fail"); return returnMap; } }

1.4.2 Postman 测试

测试:

测试结果:

2、逆向工程 better-mybatis-generator 插件

2.1 下载插件 better-mybatis-generator

2.2 自动生成代码

2.2.1 idea连接数据库

2.2.2 生成代码

2.2.2.1 选中表,右键点击 mybatis-gengrate

2.2.2.2 生成代码 设置

生成的代码:

2.3 测试

2.3.1 service

2.3.1.1 接口
public interface AirQualityService {

	//根据条件查询空气质量列表
List<AirQuality> getQualityListByExample(AirQualityExample airQualityExample); }
2.3.1.2 实现类
@Service
public class AirQualityServiceImpl implements AirQualityService { @Autowired(required = false)
private AirQualityMapper airQualityMapper; @Override
public List<AirQuality> getQualityListByExample(AirQualityExample airQualityExample) {
return airQualityMapper.selectByExample(airQualityExample);
} }

2.3.1 测试代码

@GetMapping("/airQualities")
public List<AirQuality> testAirQualityListUseBackward(){ log.info("------ 根据 查询条件,查询空气质量的列表 --------"); //创建查询条件对象
AirQualityExample airQualityExample = new AirQualityExample(); //如果需要去重,增加条件
airQualityExample.setDistinct(true); //如果需要排序,增加排序条件
airQualityExample.setOrderByClause(" id desc "); //添加自定义查询 条件,监测站名称中包含检测的
AirQualityExample.Criteria criteria = airQualityExample.createCriteria(); //criteria.andMonitorStationLike("%"+monitorStation+"%");
criteria.andMonitorStationLike("%监测%"); //区域编号 大于1
//criteria.andDidGreaterThan(1); //区域编号在指定列表中
//criteria.andDidIn(Arrays.asList(1,2,3,4,5)); //增加or的查询条件
AirQualityExample.Criteria criteriaOr = airQualityExample.createCriteria();
criteriaOr.andPm10GreaterThan(100); //拼接or的查询条件
airQualityExample.or(criteriaOr); //如果需要分页,增加分页参数 limit ${offset}, ${limit}
//起始行 (偏移量参数)
airQualityExample.setOffset(2l);
//返回数据量
airQualityExample.setLimit(5); //调用业务接口,查询空气质量列表
List<AirQuality> qualityListByExample = airQualityService.getQualityListByExample(airQualityExample); return qualityListByExample;
}

2.3.2 测试结果:

2.4 分析查询条件对象

2.4.1 基本查询条件

2.4.2 字段上的查询条件

2.5 分析 创建 xxxExample.Criteria 自定义查询条件

protected List<Criteria> oredCriteria;  //oredCriteria 是一个 Criteria 的 集合

//创建条件类 方法
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria); // 创建第一个Criteria的时候会自动加入集合中
}
return criteria;
} //or 拼接 条件 方法
public void or(Criteria criteria) {
oredCriteria.add(criteria); //其他Criteria 条件,调用方法拼接时 也会 动加入集合中
}

3、JPA

3.1 JPA 配置

# jpa 核心配置
spring:
jpa:
show-sql: true # 显示sql查询
hibernate:
ddl-auto: update #如果不存在,就新建,如果存在只更新

3.2 测试

3.2.1 实体 bean

3.2.1.1 实体类

注意

1、如果数据库没有该表自动生成该表

2、如果该表已经存在也需要填写这些注解信息,要不然会出现实体跟数据库不对应的错误

@SuppressWarnings("all") //会爆红不过没有事,抑制警告就好
@Data
@Entity
@Table(name = "air_user",catalog = "kh96_ssm_airms")
//指定jpa建表的表名,如果指定,默认使用类名作为表名,catalog是指定数据库实例名
public class AirUser { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; //用户名
@Column(name = "name",length = 32)
private String name; //密码
@Column(name = "pwd",length = 32)
private String pwd; //手机号
@Column(name = "tel",length = 11)
private String tel; }
3.2.1.2 生成的表

启动项目;

3.2.2 AirUserRepository

public interface AirUserRepository extends JpaRepository<AirUser,Integer> {

}

3.2.3 service

3.2.3.1 接口
public interface AirUserService {

    //@description : 根据用户编号,查询用户详情
AirUser getAirUserById(Integer id); }
3.2.3.2 实现类
@Service
public class AirUserServiceImpl implements AirUserService { @Autowired
private AirUserRepository airUserRepository; @Override
public AirUser getAirUserById(Integer id) {
return airUserRepository.findOne(id);
}
}

3.2.4 测试代码

@RestController
public class AirQualityController { @Autowired
private AirUserService airUserService; @GetMapping("/airUser")
public AirUser AirUserTestAirUserUserJPA(@RequestParam("Id") Integer Id){ return airUserService.getAirUserById(Id); } }

3.2.5 测试结果

3.3 分页条件查询

3.3.1 service

3.3.1.1 接口
public interface AirUserService {
//根据 name 模糊查询,根据 tel 精确查询 ,分页查询 用户列表
List<AirUser> getAirUsersByPage(String name,String tel,Integer pageNo,Integer pageSize); }
3.3.1.2 实现类
  1. 创建查询实体对象

    • AirUser airUserForm = new AirUser();
  2. 创建条件查询对象,放入查询实体对象和匹配器

    • Example<AirUser> airUserExample = Example.of(airUserForm,matching);
    1. 创建匹配器

      • ExampleMatcher matching = ExampleMatcher.matching();
    2. 组装查询条件
      • matching = matching.withMatcher("name", matcher -> matcher.contains());
      • matching = matching.withMatcher("tel",matcher -> matcher.exact());
  3. 创建排序对象

    • Sort sort = new Sort(order);
    1. 定义排序规则

      • Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
  4. 通过条件对象 和 分页对象 分页条件 查询

    • ​ Page<AirUser> airUserPage = airUserRepository.findAll(airUserExample, pageRequest);
    • airUserPage 可以获取,符合条件的总条数,总页数,分页后的数据
@Service
public class AirUserServiceImpl implements AirUserService { @Autowired
private AirUserRepository airUserRepository; @Override
public List<AirUser> getAirUsersByPage(String name, String tel, Integer pageNo, Integer pageSize) { //创建查询实体对象
AirUser airUserForm = new AirUser();
airUserForm.setName(name);
airUserForm.setTel(tel); //创建匹配器,组装查询条件
ExampleMatcher matching = ExampleMatcher.matching();
//注意:propertyPath 实体属性
//注意这里添加一个条件后一点过要重新接收返回的 ExampleMatcher 否者条件没有添加进去
matching = matching.withMatcher("name", matcher -> matcher.contains());// 模糊查询name
matching = matching.withMatcher("tel",matcher -> matcher.exact()); //精确查询电话 //创建条件查询对象,放入 查询实体 和 匹配器
Example<AirUser> airUserExample = Example.of(airUserForm,matching); //一步到位,简洁方便 推荐
// Example<AirUser> airUserExample = Example.of(airUserForm, ExampleMatcher.matching()
// .withMatcher("name", matcher -> matcher.contains())
// .withMatcher("tel", matcher -> matcher.exact())); //定义排序规则
Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
//sort 对象封装排序规则
Sort sort = new Sort(order); //分页对象 @param page zero-based page index. 所以我们的页码需要减1 处理
//放入 分页参数 和排序规则
PageRequest pageRequest = new PageRequest(pageNo - 1, pageSize,sort); //通过条件对象 和 分页对象 分页条件 查询
Page<AirUser> airUserPage = airUserRepository.findAll(airUserExample, pageRequest); // 查询返回的分页对象中,可以获取符合条件的所有条数
// long totalCount = airUserPage.getTotalElements();
//可以获取总页数
// int totalPages = airUserPage.getTotalPages(); //获取分页条件查询的 数据
List<AirUser> airUserList = airUserPage.getContent(); return airUserList;
} }

3.3.2 测试

3.2.2.1 请求
//根据 name 模糊查询,根据 tel 精确查询 ,分页查询 用户列表
@GetMapping("/getAirUsersByPage")
public List<AirUser> getAirUsersByPage(@RequestParam(value = "name",required = false,defaultValue = "") String name,
@RequestParam(value = "tel",required = false,defaultValue = "13501020304") String tel,
@RequestParam(value = "pageNo",required = false,defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize",required = false,defaultValue = "3") Integer pageSize){
log.info("------ 根据 name 模糊查询,根据 tel 精确查询 ,分页查询 用户列表 ------"); return airUserService.getAirUsersByPage(name, tel, pageNo, pageSize); }
3.2.2.2 测试结果

3.4 ExampleMatcher.GenericPropertyMatchers(通用属性匹配器)的查询方式

方法名 作用
ignoreCase 与字符串不区分大小写的匹配
caseSensitive 与字符串区分大小写的匹配
contains 与字符串模糊匹配,%{str}%
endsWith 与字符串模糊匹配,%{str}
startsWith 与字符串模糊匹配,{str}%
exact 与字符串精确匹配
storeDefaultMatching 默认匹配模式
regex 将字符串视为正则表达式进行匹配

jpa 模糊查询部分参考:-->https://blog.csdn.net/weixin_43481812/article/details/115615691

3.5 指定 jpa 自动创建表的字符集

3.5.1 自定义 配置类

// 如果数据库默认建表不是utf-8字符集,增加一个类,解决jpa自动创建表,字符集不支持中文(主要是8一下的数据库有足够问题)
public class MyMySQL57InnoDBDialect extends MySQL57InnoDBDialect {
@Override
public String getTableTypeString() {
return " ENGINE=InnoDB DEFAULT CHARSET=utf8 ";
}
}

3.5.2 配置

spring:
jpa:
properties:
hibernate:
dialect: com.kgc.sbt.config.MyMySQL57InnoDBDialect
# 自定义 配置类的路径

4、Mybatis-plus

4.1 依赖

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>

4.2 配置

4.2.1 mybatis-plus配置

#mybatis-plus 配置
mybatis-plus:
configuration:
map-underscore-to-camel-case: true #下划线映射驼峰
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启 mybatis 标准日志

4.2.2 mybatis-plus的分页拦截器

mybatis-plus的分页拦截器,有这个分页才有效果;

@Configuration
public class MybatisPlusConfig { // mybatis-plus的分页拦截器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return mybatisPlusInterceptor;
} }

4.3 条件分页查询

4.3.1 mapper

注意:要@MapperScan("com.kgc.sbt.mapper");

public interface ContactMapper extends BaseMapper<Contact> {

    //特殊sql,可以自己添加 接口并实现

}

4.3.2 service

4.3.2.1 接口
// 根据 联系人 姓名 获取联系人详情
List<ContactVO> getContactByName(String contactName,Integer pageNo,Integer pageSize);
2.3.2.2 实现类
  1. 创建查询对象

    • QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
  2. 拼接查询条件
    • contactQueryWrapper.likeRight("cname",contactName);
      contactQueryWrapper.orderByDesc("id");、
  3. or 条件拼接
    • contactQueryWrapper.or().eq("cname","李四");
  4. 创建分页对象
    • Page<Contact> contactPage = new Page<>(pageNo,pageSize);
  5. 查询联系人对象
    • Page<Contact> contactResultPage = contactMapper.selectPage(contactPage, contactQueryWrapper);
  6. 处理返回的结果结果列表
    • BeanUtils.copyProperties(contact,contactVO);
@Override
public List<ContactVO> getContactByName(String contactName, Integer pageNo, Integer pageSize) { //mybatis-plus,创建一个查询对象,直接用
QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
contactQueryWrapper.likeRight("cname",contactName);
contactQueryWrapper.orderByDesc("id"); //or 条件拼接
contactQueryWrapper.or().eq("cname","李四"); //创建分页对象
Page<Contact> contactPage = new Page<>(pageNo,pageSize); //查询联系人对象
Page<Contact> contactResultPage = contactMapper.selectPage(contactPage, contactQueryWrapper); //处理返回的结果结果列表,将状态进行转化为描述
List<ContactVO> contactVOList = contactResultPage.getRecords().stream().map(contact -> {
//创建新的VO 实体对象
ContactVO contactVO = new ContactVO();
//拷贝实体属性
BeanUtils.copyProperties(contact,contactVO);
//处理状态说明(可以定义枚举,也可以定义工具类)
contactVO.setStatusDesc(contact.getStatus() == 1 ? "正常" : "异常");
return contactVO;
}).collect(Collectors.toList()); log.info("------ 总页数:{},总条数:{},当前页:{},条数:{} -----",contactPage.getPages(),contactPage.getCurrent(),pageNo,pageSize); return contactVOList;
}

4.4.4 请求测试

@@GetMapping("/contactByPage")
public RequestResult<List<ContactVO>> getContactListByPage(@RequestParam(value = ("contactName"),required = false) String contactName,
@RequestParam(value = ("pageNo"),required = false,defaultValue = "1") Integer pageNo,
@RequestParam(value = ("pageSize"),required = false,defaultValue = "3") Integer pageSize){ return ResultBuildUtil.success(contactService.getContactByName(contactName,pageNo,pageSize));
}

测试结果:

SpringBoot(四) - 整合Mybatis,逆向工程,JPA,Mybatis-plus的更多相关文章

  1. mybatis逆向工程(MyBatis Generator)

    mybatis逆向工程(MyBatis Generator) 1. 什么是mybatis逆向工程 mybatis官方为了提高开发效率,提高自动对单表生成sql,包括 :mapper.xml.mappe ...

  2. SpringBoot (四) - 整合Mybatis,逆向工程,JPA

    1.SpringBoot整合MyBatis 1.1 application.yml # 数据源配置 spring: datasource: driver-class-name: com.mysql.c ...

  3. SpringBoot 3.SpringBoot 整合 MyBatis 逆向工程以及 MyBatis 通用 Mapper

    一.添加所需依赖,当前完整的pom文件如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&qu ...

  4. mybatis0212 mybatis逆向工程 (MyBatis Generator)

    1mybatis逆向工程 (MyBatis Generator) .1什么是mybatis的逆向工程 mybatis官方为了提高开发效率,提高自动对单表生成sql,包括生成 :mapper.xml.m ...

  5. 浅析MyBatis(四):全自动写代码的MyBatis逆向工程

    在前面几篇文章中,笔者介绍了 MyBatis 的运行流程,在此基础上简单介绍了手写 MyBatis 简易框架与自定义 MyBatis 插件的步骤,相信大家对于 MyBatis 框架的使用流程已经游刃有 ...

  6. MyBatis逆向工程生成配置 generator (生成pojo、mapper.xml、mapper.java)

    MyBatis逆向工程生成 mybatis需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java.mapper.xml ...

  7. SpringBoot的学习二:整合Redis,JPA,Mybatis

    Redis介绍: 是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API 特性: Redis 与其他 key - value 缓 ...

  8. springboot集成mybatis(逆向工程),热部署以及整合Swagger2

    本文是作者原创,版权归作者所有.若要转载,请注明出处. springboot集成mybatis和mybatis-generator插件 1.新建Springboot项目(略) 2.导入相关依赖 < ...

  9. SpringBoot整合Mybatis、SpringBoot整合Spring Data JPA

    Springboot Mybatis <?xml version="1.0" encoding="UTF-8"?> <project xmln ...

  10. springboot整合mybatis增删改查(三):mybatis逆向工程

    上一篇已经把项目基本框架完善,接下来就是利用Mybatis Generator逆向工程进行mybatis的整合. 我们在创建项目开始的时候已经勾选web,mybatis,sql等,但是这些依赖还是不够 ...

随机推荐

  1. WinDbg符号配置

    符号文件介绍 它包含了应用程序二进制文件(比如:EXE.DLL等)调试信息,专门用来作调试之用,最终生成的可执行文件在运行时并不需要这个符号文件,但你的程序中所有的变量信息都记录在这个文件中.所以调试 ...

  2. Java中序列化与反序列化

    序列化(Serialization)和反序列化(Deserialization)是计算机科学中用于数据存储和传输的两种基本操作. 序列化: 序列化是将对象的状态信息转换为可以存储或传输的形式的过程.简 ...

  3. 不依赖 Spring,你会如何自实现 RabbitMQ 消息的消费(一)

    开心一刻 上午一好哥们微信我哥们:哥们在干嘛,晚上出来吃饭我:就我俩吗哥们:对啊我:那多没意思,我叫俩女的出来哥们:好啊,哈哈哈晚上吃完饭到家后,我给哥们发消息我:今天吃的真开心,下次继续哥们:开心尼 ...

  4. WordCloudStudio 支持支付宝周期性订阅

    我们很高兴地宣布,WordCloudStudio 现已支持通过支付宝 (AliPay) 的周期性订阅支付功能!无论您是需要制作精美的词云图用于演示.社交媒体.教育资源,还是其他创意项目,现在都可以更便 ...

  5. JVM调优总结:典型配置举例

    原文出处:http://developer.51cto.com/art/201201/311739.htm 一篇非常棒的关于JVM性能调优的文章,转载用于自己经常查阅 以下配置主要针对分代垃圾回收算法 ...

  6. Java方法参数太多怎么办—Part 1—自定义类型

    本文由 ImportNew - 王村平 翻译自 dzone.如需转载本文,请先参见文章末尾处的转载要求. 本文是这个系列的第一篇文章,介绍了采用自定义类型处理参数过多的问题.如果你也希望参与类似的系列 ...

  7. python系统模块之re

    正则模块re: 元字符: 字符 描述 . 除换行符外的任意字符 \ 转义字符 [...] 字符集合,匹配任务其中一个 \d 数字:[0-9] \D 非数字:[^\d] \w 单词字符[A-Za-z0- ...

  8. 前端好用API之MutationObserver

    前情 一直以来都没有好的方式可以监听元素变化,Mutation events虽然可以监听DOM树结构变化,但是因性能问题和差的兼容问题(Webkit内核不支持)并不推荐使用. MutationObse ...

  9. Less使用备忘录

    定义 Less (Leaner Style Sheets 的缩写) 是一门向后兼容的 CSS 扩展语言,动态样式语言. 使用方式 直接引入less.js文件 好处:能获取客户端的数据,从而进行进一步的 ...

  10. 阿里云最新npm地址

    npm config set registry https://registry.npmmirror.com -g