【Mybatis】03:核心配置文件深入

第三章:MyBatis核心配置文件深入


OVERVIEW

  • 第三章:MyBatis核心配置文件深入
      • 一、MyBatis核心配置文件
        • 1.typeHandlers标签
          • (1)问题引出:
          • (2)类型转换器实现:
        • 2.plugins标签
          • (1)问题引出:
          • (2)分页操作:

一、MyBatis核心配置文件

1.typeHandlers标签

无论是MyBatis在预处理语句(PreparedStatement)中设置一个参数时,

还是从结果集中取出一个值时,都会用类型处理器将获取的值以合适的方式转换成Java类型:

【Mybatis】03:核心配置文件深入_第1张图片

如果要实现类型处理器处理不支持的或非标准的数据类型,这时就必须重写类型处理器,具体如下:

  1. 实现org.apache.ibatis.type.TypeHandler接口,或者继承一个很便利的类org.apache.ibatis.type.BaseTypeHandler
  2. 选择性的将其映射到一个JDBC类型
(1)问题引出:

例如,一个Java中的Date数据类型,要将其存储到数据库的时候保存为一个1970年至今的毫秒数,

而从数据库中取出时自动转换为Java的Date类型,这时要重写TypeHandler接口(即实现Date与数据库varchar毫秒值间的类型转换)

  1. 定义转换类继承BaseTypeHandler,覆盖4个实现的方法,其中:

    setNonNullParameter为java程序设置数据到数据库的回调方法,

    getNullableResult为查询时mysql字符串类型转换成java的Type类型的方法

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

  3. 测试转换是否正确

【Mybatis】03:核心配置文件深入_第2张图片

package com.itcast.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 getPassward() {
        return password;
    }

    public void setPassward(String passward) {
        this.password = passward;
    }

    /*方便测试与打印生成tostring方法*/
    @Override
    public java.lang.String toString() {
        return "User{" + "id=" + id + ", username=" + username + ", passward=" + password + '}';
    }
}
package com.itcast.mapper;

import com.itcast.domain.User;

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

DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itcast.mapper.UserMapper">
    <insert id="save" parameterType="user">
        insert into user value(#{id}, #{username}, #{password}, #{birthday})
    insert>
mapper>
package com.itcast.test;

import com.itcast.domain.User;
import com.itcast.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;

public class MapperTest {
    @Test
    public void test1() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //mybatis实现dao层
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //1.模拟user
        User user = new User();
        user.setUsername("lch");
        user.setPassward("abcde");
        user.setBirthday(new Date());
        //2.执行保存操作
        mapper.save(user);

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

【Mybatis】03:核心配置文件深入_第3张图片

(2)类型转换器实现:
  • step1:定义转换类继承BaseTypeHandler,覆盖4个实现的方法

【Mybatis】03:核心配置文件深入_第4张图片

package com.itcast.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> {
    //1.将java类型 转换成 数据库需要的类型
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        Long time = date.getTime();
        preparedStatement.setLong(i, time);
    }

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

    public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
        long aLong = resultSet.getLong(i);
        Date date = new Date(aLong);
        return date;
    }

    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        long aLong = callableStatement.getLong(i);
        Date date = new Date(aLong);
        return date;
    }
}
  • step2:在MyBatis核心配置文件中进行注册

DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <typeHandlers>
        <typeHandler handler="com.itcast.handler.DateTypeHandler">typeHandler>
    typeHandlers>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="20001201"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="com.itcast.mapper/UserMapper.xml">mapper>
    mappers>
configuration>
  • step3:测试
package com.itcast.test;

import com.itcast.domain.User;
import com.itcast.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;

public class MapperTest {
    @Test
    public void test1() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //mybatis实现dao层
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //1.模拟user
        User user = new User();
        user.setUsername("lch");
        user.setPassward("abcde");
        user.setBirthday(new Date());
        //2.执行保存操作
        mapper.save(user);
        sqlSession.commit();

        //3.执行查询操作
        User result = mapper.findById(10);
        System.out.println("user中的birthday:" + result.getBirthday());

        sqlSession.close();
    }
}

【Mybatis】03:核心配置文件深入_第5张图片

2.plugins标签

Mybatis可以使用第三方插件来对功能进行扩展

Mybatis插件分页助手PageHelper,是将分页的复杂操作进行封装,使用简单的方式既可获得分页的相关数据。

实现步骤:

  1. 导入通用的PageHelper坐标
  2. 在mybatis核心配置文件中配置PageHelper插件
  3. 测试分页数据获取
(1)问题引出:

DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itcast.mapper.UserMapper">
    <select id="findAll" resultType="com.itcast.domain.User">
        select * from user
    select>
mapper>
package com.itcast.mapper;

import com.itcast.domain.User;

import java.util.List;

public interface UserMapper {
    public List<User> findAll();
}
package com.itcast.test;

import com.itcast.domain.User;
import com.itcast.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 MapperTest {
    @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);

        //1.打印全部数据
        List<User> userList = mapper.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

【Mybatis】03:核心配置文件深入_第6张图片

(2)分页操作:
  • step1:pom文件导入plugin坐标
<dependency>
	<groupId>com.github.pagehelpergroupId>
	<artifactId>pagehelperartifactId>
	<version>3.7.5version>
dependency>
<dependency>
	<groupId>com.github.jsqlparsergroupId>
	<artifactId>jsqlparserartifactId>
	<version>0.9.1version>
dependency>
  • step2:修改sqlMapConfig.xml文件,配置分页助手插件

DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <typeHandlers>
        <typeHandler handler="com.itcast.handler.DateTypeHandler">typeHandler>
    typeHandlers>
    
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
        plugin>
    plugins>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="20001201"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="com.itcast.mapper/UserMapper.xml">mapper>
    mappers>
configuration>
  • step3:测试分页数据获取
package com.itcast.test;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itcast.domain.User;
import com.itcast.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 MapperTest {
    @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);

        //1.设置分页相关参数 当前页 + 每页显示条数
        PageHelper.startPage(2, 3);//查询第3-6条记录

        //2.打印全部数据
        List<User> userList = mapper.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
        //3.获取与分页相关的参数
        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());
    }
}

【Mybatis】03:核心配置文件深入_第7张图片

你可能感兴趣的:(JavaEE,Framework,java,java-ee,intellij-idea)