🍁博客主页:👉 不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒
✨系列专栏:👉 MyBatis详解
✨如果觉得博主的文章还不错的话,请三连支持一下博主。
🔥欢迎大佬指正,一起 学习!一起加油!
一、typeHandlers标签
- 可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。
- 具体做法为:
- 实现org.apache.ibatis.type.TypeHandler接口,或继承一个很便利的类org.apache.ibatis.type.BaseTypeHandler,然后可以选择性地将它映射到一个JDBC类型。
- 需求:一个Java中的Date数据类型,我想将之存到数据库的时候存成一个1970年至今的亳秒数,取出来时转换成java的Date,即java的Date与数据库的varchar毫秒值之间转换。
开发步骤:;
- 定义转换类继承类BaseTypeHandler
- 覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNllableResult为查询时mysql的字符串类型转换成java的Type类型的方法
- 在MyBatis核心配置文件中进行注册
- 测试转换是否正确
开发步骤
1.定义转换类继承类并覆盖4个未实现的方法
package com.jkj.handler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class DateTypeHandler extends BaseTypeHandler<Date> {
//将java类型转换为数据库需要的类型
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i,time);
}
//将数据库中的类型转换为java类型
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
//string 参数是要转换的字段的名称
//result查询出的结果集
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
}
//将数据库中的类型转换为java类型
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
Date date = new Date(aLong);
return date;
}
//将数据库中的类型转换为java类型
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
2.注册
<!-- 注册类型转换器-->
<typeHandlers>
<typeHandler handler="com.jkj.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
3.测试
如下,综合案例代码。
二、plugins标签
- MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据
开发步骤:
-
- 导入通用PageHelper的坐标
- 在mybatis核心配置文件中配置PageHelper插件
- 测试分页数据获取
开发步骤
1.导入PageHelper的坐标
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
2.配置PageHelper插件
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 配置数据库的方言 -->
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<!-- 5.0新版本,不需要配置方言,内部会自动识别-->
<!-- <property name="dialect" value="mysql"/>-->
</plugin>
</plugins>
注意:5.0新版本,不需要配置方言,内部会自动识别。
3.测试
//设置分页相关参数 当前页+每页显示的条数
PageHelper.startPage(2,2);
如下,综合案例代码。
三、综合代码
1.pom.xml
<?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>org.example</groupId>
<artifactId>MyBatis-config</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
</project>
2.User
package com.jkj.domain;
import java.util.Date;
public class User {
private int id;
private String username;
private String password;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
3.UserMapper
package com.jkj.dao;
import com.jkj.domain.User;
import java.util.List;
public interface UserMapper {
public void save(User user);
public User findById(int id);
public List<User> findAll();
}
4.DateTypeHandler
package com.jkj.handler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class DateTypeHandler extends BaseTypeHandler<Date> {
//将java类型转换为数据库需要的类型
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i,time);
}
//将数据库中的类型转换为java类型
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
//string 参数是要转换的字段的名称
//result查询出的结果集
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
}
//将数据库中的类型转换为java类型
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
Date date = new Date(aLong);
return date;
}
//将数据库中的类型转换为java类型
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
5.UserMapper.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.jkj.dao.UserMapper">
<insert id="save" parameterType="user">
insert into user values(#{id},#{username},#{password},#{birthday})
</insert>
<select id="findById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select>
<select id="findAll" resultType="user">
select * from user
</select>
</mapper>
6.jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisthree
jdbc.username=root
jdbc.password=root
7.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration core file-->
<configuration>
<!--通过properties标签添加properties文件-->
<properties resource="jdbc.properties"></properties>
<!--自定义别名-->
<typeAliases>
<typeAlias type="com.jkj.domain.User" alias="user"></typeAlias>
</typeAliases>
<!-- 注册类型转换器-->
<typeHandlers>
<typeHandler handler="com.jkj.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 配置数据库的方言 -->
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<!-- 5.0新版本,不需要配置方言,内部会自动识别-->
<!-- <property name="dialect" value="mysql"/>-->
</plugin>
</plugins>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--加载sql映射文件-->
<mappers>
<mapper resource="com/jkj/dao/UserMapper.xml"/>
</mappers>
</configuration>
8.MyBatisTest
package com.jkj.Test;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkj.dao.UserMapper;
import com.jkj.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class MybatisTest {
@Test
public void test() throws IOException {
User user = new User();
user.setUsername("老八");
user.setPassword("555555");
user.setBirthday(new Date());
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.save(user);
}
@Test
public void findById() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User byId = mapper.findById(5);
System.out.println(byId);
//User{id=5, username='老八', password='555555', birthday=Tue Jul 05 16:17:30 CST 2022}
}
@Test
public void findAll() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//设置分页相关参数 当前页+每页显示的条数
PageHelper.startPage(2,2);
List<User> all = mapper.findAll();
for (User user : all) {
System.out.println(user);
}
//获得与分页相关参数
PageInfo<User> userPageInfo = new PageInfo<User>(all);
System.out.println("当前页:"+userPageInfo.getPageNum());
System.out.println("每页显示条数:"+userPageInfo.getPageSize());
System.out.println("总条数:"+userPageInfo.getTotal());
System.out.println("上一页:"+userPageInfo.getPrePage());
System.out.println("下一页:"+userPageInfo.getNextPage());
System.out.println("是否是第一个:"+userPageInfo.isIsFirstPage());
System.out.println("是否是最后一个"+userPageInfo.isIsLastPage());
/*
User{id=3, username='马奎斯', password='333333', birthday=null}
User{id=4, username='罗西', password='444444', birthday=null}
当前页:2
每页显示条数:2
总条数:5
上一页:1
下一页:3
是否是第一个:false
是否是最后一个false
*/
}
}