07 mybatis核心配置文件(类型转换与分页查询)

typeHandlers标签/类型转换
java文件与 数据库字段类型转换

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。下表描述了一些默认的类型处理器(截取部分)。
在这里插入图片描述

你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。具体做法为:实现 org.apache.ibatis.type.TypeHandler 接口, 或继承一个很便利的类 org.apache.ibatis.type.BaseTypeHandler, 然后可以选择性地将它映射到一个JDBC类型。例如需求:一个Java中的Date数据类型,我想将之存到数据库的时候存成一个1970年至今的毫秒数,取出来时转换成java的Date,即java的Date与数据库的varchar毫秒值之间转换。

开发步骤:

①定义转换类继承类BaseTypeHandler

②覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法

③在MyBatis核心配置文件中进行注册

实现代码

pom.xml jdbc.properties log4j.properties 文件不变

  • User 实体类增加一个Date属性字段
package li.chen.com.business.entity;

import java.util.Date;

public class User {

    private Integer id;
    private String userName;
    private String passWord;
    private String phone;
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", phone='" + phone + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
  • DataTypeHandler 类型转换文件
package li.chen.com.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 DataTypeHandler extends BaseTypeHandler<Date> {
    //将java类型 转换成 数据库需要的类型
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        long time = date.getTime();
        preparedStatement.setLong(i,time);
    }

    //将数据库中类型 转换成 java类型
    //String参数 要转换的字段名称
    //ResultSet 查询出的结果集
    @Override
    public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
        //获得结果集中需要的数据(long),转换成Data类型,返回
        long aLong = resultSet.getLong(s);
        Date date = new Date(aLong);
        return date;
    }

    //将数据库中类型 转换成 java类型
    @Override
    public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
        //获得结果集中需要的数据(long),转换成Data类型,返回
        long aLong = resultSet.getLong(i);
        Date date = new Date(aLong);
        return date;
    }

    @Override
    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        //获得结果集中需要的数据(long),转换成Data类型,返回
        long aLong = callableStatement.getLong(i);
        Date date = new Date(aLong);
        return date;
    }
}

  • sqlMapConfig.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>

    <!--加载外部properties-->
    <properties resource="jdbc.properties"></properties>

    <!--自定义别名-->
    <typeAliases>
        <typeAlias type="li.chen.com.business.entity.User" alias="user"></typeAlias>
    </typeAliases>

    <!--注册类型处理器-->
    <typeHandlers>
        <typeHandler handler="li.chen.com.handler.DataTypeHandler"></typeHandler>
    </typeHandlers>


    <!--配置数据源环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <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>

    <!--加载映射文件-->
    <mappers>
        <mapper resource="li.chen.com.mapper\UserMapper.xml"/>
    </mappers>

</configuration>
  • UserMapper
package li.chen.com.business.mapper;

import li.chen.com.business.entity.User;
import java.util.List;

public interface UserMapper {
    public void save (User user);

    public User findById(int id);

}
  • 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="li.chen.com.business.mapper.UserMapper">
    <insert id="save" parameterType="user">
        insert into test_user(id,userName,passWord,phone,birthday) values(#{id},#{userName},#{passWord},#{phone},#{birthday})
    </insert>

    <select id="findById" parameterType="int" resultType="user">
        select * from test_user where id=#{id}
    </select>

</mapper>

  • MybatisTest 测试类
package li.chen.com.test;

import li.chen.com.business.entity.User;
import li.chen.com.business.mapper.UserMapper;
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 test3() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> userList = mapper.findAll();
        System.out.println(userList);

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void test2() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.findById(3);
        System.out.println(user);

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void test() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //执行保存
        User user = new User();
        user.setId(3);
        user.setUserName("lucay");
        user.setPassWord("8548554");
        user.setPhone("158448585");
        user.setBirthday(new Date());  //数据库是long类型

        mapper.save(user);

        sqlSession.commit();
        sqlSession.close();
    }
}

//-------
test1
17:05:29,015 DEBUG findById:159 - ==>  Preparing: select * from test_user where id=? 
17:05:29,041 DEBUG findById:159 - ==> Parameters: 3(Integer)
17:05:29,060 DEBUG findById:159 - <==      Total: 1
User{id=3, userName='lucay', passWord='8548554', phone='158448585', birthday=Tue Jan 12 17:04:26 CST 2021}

//---
test
17:04:26,509 DEBUG save:159 - ==>  Preparing: insert into test_user(id,userName,passWord,phone,birthday) values(?,?,?,?,?) 
17:04:26,539 DEBUG save:159 - ==> Parameters: 3(Integer), lucay(String), 8548554(String), 158448585(String), 1610442266314(Long)

注意查看DEBUG 中birthday字段2次数据类型

plugins标签/分页查询

MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据

①导入通用PageHelper的坐标

②在mybatis核心配置文件中配置PageHelper插件

③测试分页数据获取

实现代码

pom.xml

        <!--分页标签-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>1.0</version>
        </dependency>

sqlMapConfig.xml

    <!--配置分页助手插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--
            告诉分页插件是哪个数据库
            但是 配置此行运行会报错!!!
            <property name="dialect" value="mysql"/>
            -->
        </plugin>
    </plugins>

UserMapper

package li.chen.com.business.mapper;

import li.chen.com.business.entity.User;
import java.util.List;

public interface UserMapper {
    public void save (User user);
    public User findById(int id);

    public List<User> findAll();

}

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="li.chen.com.business.mapper.UserMapper">
    <insert id="save" parameterType="user">
        insert into test_user(id,userName,passWord,phone,birthday) values(#{id},#{userName},#{passWord},#{phone},#{birthday})
    </insert>

    <select id="findById" parameterType="int" resultType="user">
        select * from test_user where id=#{id}
    </select>

    <select id="findAll" resultType="user">
        select * from test_user
    </select>

</mapper>

MybatisTest 测试类

package li.chen.com.test;

import com.github.pagehelper.PageHelper;
import li.chen.com.business.entity.User;
import li.chen.com.business.mapper.UserMapper;
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 test3() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //设置分页相关参数 当前页+每页显示的条数
        PageHelper.startPage(2,5);

        List<User> userList = mapper.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
        
        //获取与分页相关参数
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        System.out.println("当前页:" + pageInfo.getPageNum());
        System.out.println(" 每页显示条数:" + pageInfo.getPageSize());
        System.out.println("总条数:" + pageInfo.getTotal());
        System.out.println("总页数:"+pageInfo.getPages());
        System.out.println("上一页:" + pageInfo.getPrePage());
        System.out.println("下一页:" + pageInfo.getNextPage());
        System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
        System.out.println("是否最后一页:"+pageInfo.isIsLastPage());
        
        sqlSession.commit();
        sqlSession.close();
    }

}
//------------
18:06:16,289 DEBUG findAll:159 - ==>  Preparing: select * from test_user LIMIT ?, ? 
18:06:16,290 DEBUG findAll:159 - ==> Parameters: 3(Integer), 3(Integer)
18:06:16,294 DEBUG findAll:159 - <==      Total: 3
User{id=4, userName='zhaao', passWord='32', phone='10655', birthday=null}
User{id=6, userName='lisi', passWord='123456', phone='10565455', birthday=null}
User{id=7, userName='tom', passWord='123456', phone='1758785555', birthday=null}
当前页:2
 每页显示条数:3
总条数:8
总页数:3
上一页:1
下一页:3
是否第一页:false

注意查看DEBUG 中的sql语句

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岿然如故

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值