当前位置: 首页 > news >正文

mybatis实践篇(二)

自定义类型处理器(TypeHandler)

实体
package com.wyl.mybatis.entity;import java.util.Date;/*** @Description 省市区-字典* @Author wuyilong* @Date 2024-02-26*/public class FullCity {private static final long serialVersionUID = 1L;/*** 主键ID*/private Long id;/*** 名称*/private String name;/*** 区域码*/private String code;/*** 全名称*/private String fullName;/*** 创建时间*/private String createTime;public static long getSerialVersionUID() {return serialVersionUID;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getFullName() {return fullName;}public void setFullName(String fullName) {this.fullName = fullName;}public String getCreateTime() {return createTime;}public void setCreateTime(String createTime) {this.createTime = createTime;}
}
运行程序
package com.wyl.mybatis.demo;import com.wyl.mybatis.config.SqlSessionFactoryConfig;
import com.wyl.mybatis.entity.FullCity;
import com.wyl.mybatis.mapper.FullCityMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;/*** @Description* @Author WuYiLong* @Date 2024/3/14 14:47*/
public class TypeHandlerDemo {private final static Logger log = LoggerFactory.getLogger(TypeHandlerDemo.class);public static void main(String[] args) throws IOException {SqlSessionFactory sqlSessionFactory = SqlSessionFactoryConfig.buildSqlSessionFactory();try (SqlSession sqlSession = sqlSessionFactory.openSession()) {FullCityMapper mapper = sqlSession.getMapper(FullCityMapper.class);FullCity fullCity = mapper.selectByName("广东省");log.info("数据json:{}", fullCity.getCreateTime());}}
}
类型处理器
package com.wyl.mybatis.typehandler;import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;import java.sql.*;
import java.util.Date;/*** @Description* @Author WuYiLong* @Date 2024/3/14 15:18*/
public class DateToStringTypeHandler extends BaseTypeHandler {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {}@Overridepublic String getNullableResult(ResultSet rs, String columnName) throws SQLException {Timestamp timestamp = rs.getTimestamp(columnName);if (timestamp != null) {return DateUtil.format(new Date(timestamp.getTime()),"yyyy-MM-dd HH:mm:dd.SSSSSS");}return null;}@Overridepublic Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {return null;}@Overridepublic Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {return null;}
}
mybatis-config.xml
 <typeHandlers><package name="com.wyl.mybatis.typehandler"/>
<!--        <typeHandler handler="com.wyl.mybatis.typehandler.DateToStringTypeHandler" javaType="date" jdbcType="DATE"/>--></typeHandlers>


由上面可以知道:通过自定义类型转换器,java类型和mysql类型可以无缝转换。

mybatis集成springboot

maven设置

springboot: v2.7.18
mybatis-spring-boot-starter: v2.3.2

<?xml version="1.0" encoding="UTF-8"?>
<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.wyl</groupId><artifactId>mybatis-springboot-demo</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.2</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.3.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.30</version><scope>provided</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.26</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.7.18</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version> <!-- 这里可以选择合适的版本 --><configuration><source>1.8</source> <!-- 这里指定源代码的Java版本 --><target>1.8</target> <!-- 这里指定生成字节码的Java版本 --></configuration></plugin></plugins></build>
</project>
配置文件yml
server:port: 8784spring:profiles:active: devdatasource:url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456hikari:maximum-pool-size: 15 #最大连接数,默认值10.minimum-idle: 5 #最小空闲连接,默认值10.connection-timeout: 60000 #连接超时时间(毫秒),默认值30.#空闲连接超时时间,默认值600000(10分钟),只有空闲连接数大于最大连接数且空闲时间超过该值,才会被释放#如果大于等于 max-lifetime 且 max-lifetime>0,则会被重置为0.idle-timeout: 600000max-lifetime: 1800000 #连接最大存活时间,默认值30分钟.设置应该比mysql设置的超时时间短connection-test-query: select 1 #连接测试查询auto-commit: truepool-name: HikariCP # 连接池名称# mybatis
mybatis:mapper-locations: classpath:/mapper/**type-aliases-package: com.wyl.boot.entity
demo结构

启动完成

上面已经完成了mybatis和springboot的集成,包括一些主要的启动配置、文件夹的分布、maven包的下载

多数据源配置

数据库配置文件
# mysql
db.username=root
db.password=root
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/blog?zeroDateTimeBehavior=CONVERT_TO_NULL&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=GMT%2B8# pgsql
db1.username=postgres
db1.password=1234
db1.driver=org.postgresql.Driver
db1.url=jdbc:postgresql://127.0.0.1:5432/postgres?reWriteBatchedInserts=true&stringtype=unspecified
mybatis的配置文件
 <!-- 环境:配置mybatis的环境 --><environments default="development"><!-- 环境变量:可以配置多个环境变量,比如使用多数据源时,就需要配置多个环境变量 --><environment id="development"><!-- 事务管理器 --><transactionManager type="jdbc"></transactionManager><!-- 数据源 --><dataSource type="POOLED"><property name="driver" value="${db.driver}"/><property name="url" value="${db.url}"/><property name="username" value="${db.username}"/><property name="password" value="${db.password}"/></dataSource></environment><environment id="pgsql"><transactionManager type="jdbc"></transactionManager><dataSource type="POOLED"><property name="driver" value="${db1.driver}"/><property name="url" value="${db1.url}"/><property name="username" value="${db1.username}"/><property name="password" value="${db.password}"/></dataSource></environment></environments>
实体类
package com.wyl.mybatis.entity;/*** @Description 省市区-字典* @Author wuyilong* @Date 2024-02-26*/
public class FullCity {private static final long serialVersionUID = 1L;/*** 主键ID*/private Long id;/*** 名称*/private String name;/*** 区域码*/private String code;/*** 全名称*/private String fullName;/*** 创建时间*/private String createTime;public static long getSerialVersionUID() {return serialVersionUID;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getFullName() {return fullName;}public void setFullName(String fullName) {this.fullName = fullName;}public String getCreateTime() {return createTime;}public void setCreateTime(String createTime) {this.createTime = createTime;}
}
package com.wyl.mybatis.entity;/*** @Description* @Author WuYiLong* @Date 2024/3/22 21:47*/
public class User {/*** 主键id*/private Long id;/*** 用户名*/private String username;/*** 密码*/private String password;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}
mapper接口

/*** @Description* @Author WuYiLong* @Date 2024/3/22 21:48*/
@Mapper
public interface UserMapper {/*** 列表查询* @return*/@Select("select * from public.user")List<User> selectList();}
package com.wyl.mybatis.mapper;import com.wyl.mybatis.entity.FullCity;
import com.wyl.mybatis.page.Page;
import com.wyl.mybatis.req.FullCityReq;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;import java.util.List;/**
* @Description 省市区-字典
* @Author wuyilong
* @Date 2024-02-26
*/
@Mapper
public interface FullCityMapper {/*** 根据名称查询* @param name* @return*/FullCity selectByName(@Param("name") String name);/*** 根据名称和code查询* @param name* @param code* @return*/@Select(value = "select * from d_full_city where name = #{name} and code = #{code}")FullCity selectByNameAndCode(@Param("name") String name,@Param("code") String code);/*** 查询省市区* @param fullCityReq* @return*/@Select(value = "select * from d_full_city where name = #{fullCityReq.name}")FullCity selectFullCity(@Param("fullCityReq") FullCityReq fullCityReq);/*** 省市区模糊查询* @param name* @return*/@Select(value = "select * from d_full_city where name regexp #{name}")List<FullCity> selectFullCityLikeName(@Param("name")  String name);/*** 分页* @param page* @return*/@Select("select * from d_full_city")List<FullCity> selectFullCityPage(@Param("page") Page page);/*** 统计表的数量* @param table* @return*/@Select("select count(*) count from #{table}")Integer countTable(@Param("table") String table);
}
数据库加载配置文件
package com.wyl.mybatis.config;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;/*** @Description* @Author WuYiLong* @Date 2024/3/14 9:43*/
public class SqlSessionFactoryConfig {/*** 默认配置* @return* @throws IOException*/public static SqlSessionFactory buildSqlSessionFactory() throws IOException {// 读取mybatis的配置文件InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 通过SqlSessionFactoryBuilder 的 build 方法用于解析配置文件并创建 SqlSessionFactory 对象。SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);return sqlSessionFactory;}/*** 多环境配置* @param environment* @return* @throws IOException*/public static SqlSessionFactory buildSqlSessionFactoryEnv(String environment) throws IOException {// 读取mybatis的配置文件InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 通过SqlSessionFactoryBuilder 的 build 方法用于解析配置文件并创建 SqlSessionFactory 对象。SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,environment);return sqlSessionFactory;}
}
package com.wyl.mybatis.demo;import com.wyl.mybatis.config.SqlSessionFactoryConfig;
import com.wyl.mybatis.entity.FullCity;
import com.wyl.mybatis.entity.User;
import com.wyl.mybatis.mapper.FullCityMapper;
import com.wyl.mybatis.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.util.List;/*** @Description* @Author WuYiLong* @Date 2024/3/22 21:16*/
public class MoreDataSource {private static final Logger log = LoggerFactory.getLogger(MoreDataSource.class);public static void main(String[] args) throws IOException {// mysqlSqlSessionFactory sqlSessionFactory = SqlSessionFactoryConfig.buildSqlSessionFactory();try (SqlSession sqlSession = sqlSessionFactory.openSession()) {FullCityMapper mapper = sqlSession.getMapper(FullCityMapper.class);FullCity fullCity = mapper.selectByName("广东省");System.out.println("区域名称:" + fullCity.getFullName());}// postgresqlSqlSessionFactory pgsql = SqlSessionFactoryConfig.buildSqlSessionFactoryEnv("pgsql");try (SqlSession sqlSession = pgsql.openSession()) {UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> users = mapper.selectList();for (User user : users) {log.info("用户名称:{},密码:{}",user.getUsername(),user.getPassword());}}}
}

相关文章:

  • OSPF-1类Router LSA学习
  • 2024 年广西职业院校技能大赛高职组《云计算应用》赛项赛题第 2 套
  • Java设计模式之单例模式(多种实现方式)
  • 手撕算法-删除链表的倒数第 N 个结点
  • 抖音IP属地怎么更改
  • pta-洛希极限
  • PostgreSQL关系型数据库介绍与部署
  • [AIGC] Redis基础命令集详细介绍
  • Git——IDEA中的使用详解
  • 【Android 内存优化】Koom核心内存指标分析
  • C++一维数组练习oj(3)
  • Android kotlin全局悬浮窗全屏功能和锁屏页面全屏悬浮窗功能二
  • 赋能数据收集:从机票网站提取特价优惠的JavaScript技巧
  • 最近接到一个大项目,给公司设计抢商品代金劵业务
  • 洛谷P3372 线段树
  • [译]如何构建服务器端web组件,为何要构建?
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • HTML5新特性总结
  • Javascripit类型转换比较那点事儿,双等号(==)
  • JS 面试题总结
  • Mac转Windows的拯救指南
  • Node.js 新计划:使用 V8 snapshot 将启动速度提升 8 倍
  • oldjun 检测网站的经验
  • Python 反序列化安全问题(二)
  • Swift 中的尾递归和蹦床
  • Vim 折腾记
  • webgl (原生)基础入门指南【一】
  • windows下使用nginx调试简介
  • WordPress 获取当前文章下的所有附件/获取指定ID文章的附件(图片、文件、视频)...
  • 表单中readonly的input等标签,禁止光标进入(focus)的几种方式
  • 高程读书笔记 第六章 面向对象程序设计
  • 给自己的博客网站加上酷炫的初音未来音乐游戏?
  • 前端工程化(Gulp、Webpack)-webpack
  • 浅谈Golang中select的用法
  • 如何胜任知名企业的商业数据分析师?
  • 深入浅出Node.js
  • 什么是Javascript函数节流?
  • 我从编程教室毕业
  • 项目实战-Api的解决方案
  • 一起来学SpringBoot | 第十篇:使用Spring Cache集成Redis
  • 用quicker-worker.js轻松跑一个大数据遍历
  • ​用户画像从0到100的构建思路
  • ###51单片机学习(1)-----单片机烧录软件的使用,以及如何建立一个工程项目
  • #pragma pack(1)
  • %3cli%3e连接html页面,html+canvas实现屏幕截取
  • ()、[]、{}、(())、[[]]命令替换
  • (13)[Xamarin.Android] 不同分辨率下的图片使用概论
  • (ISPRS,2023)深度语义-视觉对齐用于zero-shot遥感图像场景分类
  • (附源码)springboot助农电商系统 毕业设计 081919
  • (蓝桥杯每日一题)love
  • (论文阅读40-45)图像描述1
  • (深入.Net平台的软件系统分层开发).第一章.上机练习.20170424
  • (转)PlayerPrefs在Windows下存到哪里去了?
  • (转载)跟我一起学习VIM - The Life Changing Editor
  • *setTimeout实现text输入在用户停顿时才调用事件!*