自定义类型处理器(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 {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
}
@Override
public 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;
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return null;
}
@Override
public 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: 8784
spring:
profiles:
active: dev
datasource:
url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
hikari:
maximum-pool-size: 15 #最大连接数,默认值10.
minimum-idle: 5 #最小空闲连接,默认值10.
connection-timeout: 60000 #连接超时时间(毫秒),默认值30秒.
#空闲连接超时时间,默认值600000(10分钟),只有空闲连接数大于最大连接数且空闲时间超过该值,才会被释放
#如果大于等于 max-lifetime 且 max-lifetime>0,则会被重置为0.
idle-timeout: 600000
max-lifetime: 1800000 #连接最大存活时间,默认值30分钟.设置应该比mysql设置的超时时间短
connection-test-query: select 1 #连接测试查询
auto-commit: true
pool-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 {
// mysql
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryConfig.buildSqlSessionFactory();
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
FullCityMapper mapper = sqlSession.getMapper(FullCityMapper.class);
FullCity fullCity = mapper.selectByName("广东省");
System.out.println("区域名称:" + fullCity.getFullName());
}
// postgresql
SqlSessionFactory 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());
}
}
}
}