typeHandlers标签和plugins标签

本文阅读 3 分钟
首页 代码,Java 正文

img

开发步骤

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.测试

如下,综合案例代码。

img

开发步骤

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 */
    }
}
本文为互联网自动采集或经作者授权后发布,本文观点不代表立场,若侵权下架请联系我们删帖处理!文章出自:https://blog.csdn.net/qq_43514330/article/details/125625447
-- 展开阅读全文 --
安全面试之XSS(跨站脚本攻击)
« 上一篇 07-24

发表评论

成为第一个评论的人

热门文章

标签TAG

最近回复