Spring Boot系列7-SpringBoot+mybatis+druid+TypeHandler

2024-08-26 09:48

本文主要是介绍Spring Boot系列7-SpringBoot+mybatis+druid+TypeHandler,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

点击阅读原文
介绍在SpringBoot中集成mybatis和druid以及自定义TypeHandler

创建数据库表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- 创建student表
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',`parent_phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '家长电话号码逗号分隔',`city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '居住城市json格式存储{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}',`net_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '网名逗号分隔',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- 插入学生信息
-- ----------------------------
INSERT INTO `student` VALUES (1, '小英', '13222222222,13333333333,15777777777', '{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}', '会飞的鱼,小小雪,茉莉香果果');
INSERT INTO `student` VALUES (2, '小明', '13222222222,13333333333,15777777777', '{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}', '会飞的鱼2,小小雪2,茉莉香果果2');SET FOREIGN_KEY_CHECKS = 1;

xml方式

在pom.xml添加mybatis,druid,mysql驱动配置
    <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><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
在application.yml中配置mybatis
# 使用druid数据源
spring:datasource:druid:driver-class-name: com.mysql.jdbc.Driverfilters: statmaxActive: 20initialSize: 1maxWait: 60000minIdle: 1timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: select 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truemaxOpenPreparedStatements: 20db-type: com.alibaba.druid.pool.DruidDataSourcethymeleaf:cache: falsemybatis:type-handlers-package:  com.tiankonglanlande.cn.springboot.mybatis.typehandlermapperLocations: classpath:mapper/**.xmltypeAliasesPackage:  com.tiankonglanlande.cn.springboot.mybatis.bean# 开启自动映射configuration:map-underscore-to-camel-case: truelazy-loading-enabled: falseauto-mapping-behavior: full
数据库信息相关配置
spring.datasource.url = jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding-utf8&allowMultiQueries=true
spring.datasource.username= root
spring.datasource.password= root
启动文件相关配置
@SpringBootApplication
@MapperScan("com.tiankonglanlande.cn.springboot.mybatis.dao")
public class MybatisDruidApplication {public static void main(String[] args) {SpringApplication.run(MybatisDruidApplication.class, args);}
}

说明:@MapperScan扫描注入指定的包名下Mapper接口注入容器

编写数据库表对应的Student实体类
/*** 学生实体类*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Serializable {private String id;private String name;private String parentPhone;private String city;private String netName;
}
编写StudentDao Mapper接口
public interface StudentDao {/*** 查询所有的学生信息* @return*/List<Student> selectStudentList();}
编写StudentDao.xml Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.tiankonglanlande.cn.springboot.mybatis.dao.StudentDao" ><select id="selectStudentList" resultType="Student">SELECT * FROM student</select></mapper>
编写StudentService
@Service
public class StudentService {@Autowiredprivate StudentDao studentDao;public List<Student> selectStudentList(){return studentDao.selectStudentList();}
}
编写StudentController
@RestController
public class StudentController {@Autowiredprivate StudentService studentService;@RequestMapping("/students")public List<Student> selectStudentList(){List<Student> students = studentService.selectStudentList();return students;}
}
在浏览器访问:http://localhost:8080/students得到结果
[{"id": "1","name": "小英","parentPhone": "13222222222,13333333333,15777777777","city": "{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}","netName": "会飞的鱼,小小雪,茉莉香果果"},{"id": "2","name": "小明","parentPhone": "13222222222,13333333333,15777777777","city": "{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}","netName": "会飞的鱼2,小小雪2,茉莉香果果2"}
]

使用纯注解方式

StudentDao添加方法selectStudentListByAnnotation
    @Select("SELECT * FROM student")List<Student> selectStudentListByAnnotation();
StudentService添加方法selectStudentListByAnnotation
public List<Student> selectStudentListByAnnotation(){return studentDao.selectStudentListByAnnotation();}
StudentController調用
@RequestMapping("/students2")public List<Student> selectStudentListByAnnotation(){List<Student> students = studentService.selectStudentListByAnnotation();return students;}
在浏览器访问:http://localhost:8080/students得到与xml访问相同的结果
[{"id": "1","name": "小英","parentPhone": "13222222222,13333333333,15777777777","city": "{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}","netName": "会飞的鱼,小小雪,茉莉香果果"},{"id": "2","name": "小明","parentPhone": "13222222222,13333333333,15777777777","city": "{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}","netName": "会飞的鱼2,小小雪2,茉莉香果果2"}
]

解决上面返回json数据的问题

从上面json的数据可以看出parentPhone和netName是多条数据通过逗号拼接成的一个字段,还有city是json字符串组成的文本
这样前端拿到数据可能还需要进行处理成集合再遍历出来;city是一个json字符串文本,要想转化成json还需要一番周折,
那么作为认真负责的后台开发的我们可以使用Mybatis的TypeHandler将parentPhone和netName转化成集合,将city转化成标准的json方便前端绑定数据。

处理逗号拼接的字符串为集合

首先我们看之前在application.yml中配置mybatis的一段代码

mybatis:type-handlers-package:  com.tiankonglanlande.cn.springboot.mybatis.typehandler

说明:这一段代码会扫描com.tiankonglanlande.cn.springboot.mybatis.typehandler包下面的TypeHandler注入到spring容器

修改一下Student实体属性为集合
/*** 学生实体类*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Serializable {private String id;private String name;private String[] parentPhone;//此处修改为数组对象private String city;private String[] netName;//此处修改为数组对象
}
自定义typehandler
/*** 字符串转int数组*/
public class StringArrayTypeHandler extends BaseTypeHandler<String[]>{private static final String delimiter=",";@Overridepublic void setNonNullParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {List<String> list=new ArrayList<>();for (String item:strings){list.add(String.valueOf(item));}preparedStatement.setString(i,String.join(delimiter,list));}@Overridepublic String[] getNullableResult(ResultSet resultSet, String s) throws SQLException {String str=resultSet.getString(s);if (resultSet.wasNull()){return null;}return str.split(delimiter);}@Overridepublic String[] getNullableResult(ResultSet resultSet, int i) throws SQLException {String str= resultSet.getString(i);if (resultSet.wasNull()){return null;}return str.split(delimiter);}@Overridepublic String[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {String str= callableStatement.getString(i);if (callableStatement.wasNull()){return null;}return str.split(delimiter);}
}

说明:setNonNullParameter方法会在保存数据库之前执行,我们在此方法将保存的数组使用逗号拼接还原数据库存储方式
其他方法是从数据库取出数据时mybatis将把数据映射成实体类执行,此时我们将逗号拼接的字符串转换为数组形式

验收逗号拼接字符串转换为数组成果

浏览器输入http://localhost:8080/students可以看到原先逗号拼接的字符串已经转换为集合对象

[{"id": "1","name": "小英","parentPhone": ["13222222222","13333333333","15777777777"],"city": "{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}","netName": ["会飞的鱼","小小雪","茉莉香果果"]},{"id": "2","name": "小明","parentPhone": ["13222222222","13333333333","15777777777"],"city": "{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"}","netName": ["会飞的鱼2","小小雪2","茉莉香果果2"]}
]
解决最后一个问题:将city转化成标准的json方便前端绑定数据

定义CityBean


@Data
@AllArgsConstructor
@NoArgsConstructor
public class CityBean implements Serializable{private String province;private String city;private String district;
}

修改Student将CityBean作为他的属性


/*** 学生实体类*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Serializable {private String id;private String name;private String[] parentPhone;//此处修改为数组对象private CityBean city;//修改为CityBean类private String[] netName;//此处修改为数组对象
}

定义JsonCityBeanTypeHandler


public class JsonCityBeanTypeHandler extends BaseTypeHandler<CityBean> {public ObjectMapper objectMapper=new ObjectMapper();@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, CityBean t, JdbcType jdbcType) throws SQLException {try {ps.setString(i,objectMapper.writeValueAsString(t));} catch (JsonProcessingException e) {e.printStackTrace();}}@Overridepublic CityBean getNullableResult(ResultSet resultSet, String s) throws SQLException {String str=resultSet.getString(s);if (resultSet.wasNull()){return null;}return getBean(str);}@Overridepublic CityBean getNullableResult(ResultSet resultSet, int i) throws SQLException {return null;}@Overridepublic CityBean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {return null;}private CityBean getBean(String str){if (StringUtils.isEmpty(str))return null;try {return objectMapper.readValue(str,CityBean.class);} catch (IOException e) {e.printStackTrace();}return null;}
}

如果是存储的是json集合字符串可以这样

修改student表添加一个visited字段(数据随便插入的不要当真哈!)


alter table student add visited varchar(256) COMMENT '去过的地方jsonarray存储[{"province":"广东省","city":"深圳市","district":"南山区"}]';
UPDATE student SET visited='[{"province":"四川省","city":"深圳市","district":"南山区"}]' WHERE id=1;
UPDATE student SET visited='[{"province":"四川省","city":"深圳市","district":"南山区"},{"province":"广东省","city":"成都市","district":"青羊区"}]' WHERE id=2;

定义VisitedBean

/*** 去过的地方*/
public class VisitedBean extends CityBean{}

定义JsonListTypeHandler


/*** json集合字符串转集合* @param <T>*/
public class JsonListTypeHandler<T> extends BaseTypeHandler<List<T>> {public static ObjectMapper objectMapper = new ObjectMapper();@Overridepublic void setNonNullParameter(PreparedStatement ps, int i,  List<T> parameter, JdbcType jdbcType) throws SQLException {try {ps.setString(i, objectMapper.writeValueAsString(parameter));} catch (JsonProcessingException e) {e.printStackTrace();}}@Overridepublic List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {String str = rs.getString(columnName);if (rs.wasNull())return null;return getBeanList(str);}@Overridepublic List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {String str = rs.getString(columnIndex);if (rs.wasNull())return null;return getBeanList(str);}@Overridepublic List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {String str = cs.getString(columnIndex);if (cs.wasNull())return null;return getBeanList(str);}private List<T> getBeanList(String str) {if (StringUtils.isEmpty(str)){return null;}try {List<T> beanList =objectMapper.readValue(str,new TypeReference<List<T>>(){});return beanList;} catch (IOException e) {e.printStackTrace();return null;}}
}

测试结果,浏览器输入:http://localhost:8080/students
结果如下:

[{"id": "1","name": "小英","parentPhone": ["13222222222","13333333333","15777777777"],"city": {"province": "广东省","city": "深圳市","district": "南山区"},"visited": [{"province": "四川省","city": "深圳市","district": "南山区"}],"netName": ["会飞的鱼","小小雪","茉莉香果果"]},{"id": "2","name": "小明","parentPhone": ["13222222222","13333333333","15777777777"],"city": {"province": "广东省","city": "深圳市","district": "南山区"},"visited": [{"province": "四川省","city": "深圳市","district": "南山区"},{"province": "广东省","city": "成都市","district": "青羊区"}],"netName": ["会飞的鱼2","小小雪2","茉莉香果果2"]}
]

源码下载链接

作者:天空蓝蓝的,版权所有,欢迎保留原文链接进行转载:)

这篇关于Spring Boot系列7-SpringBoot+mybatis+druid+TypeHandler的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1108218

相关文章

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.