Mybatis动态sql语句编写、自定义类型转换器typeHandler学习、pageHelper插件的使用

目录

一、动态sql语句编写

1.1  标签介绍

2、简单示例

二、自定义类型转换器typeHandler学习

1、自定义类型转换器typeHandler的原因与步骤:

2、 自定义示例 (将DATE类型的数据转换为时间戳存储到数据库中)

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

三、pageHelper插件的使用

1、在pom.xml导入坐标

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

3、调用pageHelper

4、分页结果展示


一、动态sql语句编写

1.1  标签介绍

1.1.1 if标签
if标签通常用于WHERE语句、UPDATE语句、INSERT语句中,通过判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值。
1.1.2 chose标签
MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。
    属性介绍:
        collection:collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合。
        item :表示在迭代过程中每一个元素的别名
        index :表示在迭代过程中每次迭代到的位置(下标)
        open :前缀
        close :后缀
        separator :分隔符,表示迭代时每个元素之间以什么分隔
1.1.3 where标签
用于替换where 1=1的标签
1.1.4 set 标签
当在update语句中使用if标签时,如果最后的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置set关键字,和剔除追加到条件末尾的任何不相关的逗号。
1.1.5 trim标签
trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略),可以完成set或者是where标记的功能。
属性介绍:
    prefix:前缀覆盖并增加其内容
    suffix:后缀覆盖并增加其内容
    prefixOverrides:前缀判断的条件
    suffixOverrides:后缀判断的条件

2、简单示例

2.1 pojo类:User

    private int id;
    private int age;
    private String username;
    private Date birthday;

2.2 Usermapper接口

public interface UserMapper {

    /**
     * 根据条件查用户(where if 标签)
     * @param user
     * @return
     */
    public User findUser1(User user);

    /**
     * 根据条件查用户(where choose、when、otherwise 标签)
     * @param user
     * @return
     */
    public User findUserByCondition2(User user);

    /**
     * 根据条件查用户(trim 标签)
     * @param user
     * @return
     */
    public User findUserByCondition3(User user);

    /**
     * 根据多个id查询用户(foreach标签)
     * @param ids
     * @return
     */

    public List<User> findUsersByIds(List<Integer> ids);

    /**
     * 批量插入user(foreach标签)
     * @param users
     */
    public void insertUserList(List<User> users);

    /**
     * 查询所有用户,演示pageHelper插件
     * @return
     */
    public List<User> findAll();

    /**
     * 更新用戶set标签
     * @param user
     */
    public void updateUser(User user);
}

2.3 sql语句的抽取与引用

  抽取:<sql id="selectUser"> select * from user </sql>
  引用:<include refid="selectUser"></include>

2.4 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.bienan.mapper.UserMapper">
    <!--抽取sql语句避免重复-->
    <sql id="selectUser"> select * from user </sql>

    <!--where if 条件查询用户-->
    <select id="findUser1" parameterType="User" resultType="User">
        -- include 引用被抽取的sql语句
       <include refid="selectUser"></include>
        <where>
            <if test="id!=null and id!=''">
               and id=#{id}
            </if>
            <if test="username!=null and username!=''">
              and  username=#{username}
            </if>
            <if test="age!=null and age!=''">
                and age=#{age}
            </if>
        </where>
    </select>


    <!--根据多个id 批量查询用户(foreach标签)-->
    <select id="findUsersByIds" parameterType="list" resultType="User">
        <include refid="selectUser"></include>
        <where>
            <foreach collection="list" open="id in (" close=")" item="id" separator=",">
                #{id}
            </foreach>
        </where>
    </select>

    <!--添加用户-->
    <select id="saveUser" parameterType="User">
        insert into user(id,username,age,birthday) values (#{id},#{username},#{age},#{birthday})
    </select>

    <!--动态Sql: foreach标签, 批量插入-->
    <insert id="insertUserList" useGeneratedKeys="true" keyProperty="id">
        insert into user (username, age, birthday)
        values
        <foreach collection="list" item="user" separator="," >
            (#{user.username}, #{user.age}, #{user.birthday})
        </foreach>
    </insert>

    <!--otherwise 根据任意一个条件查询用户-->
    <select id="findUserByCondition2" parameterType="User" resultType="User">
        <include refid="selectUser"></include>
        <where>
            <choose>
                <when test="age!=null and age!=''">
                    and age=#{age}
                </when>
                <when test="username!=null and username!=''">
                    and username=#{username}
                </when>
                <otherwise>
                    and id=#{id}
                </otherwise>
            </choose>
        </where>
    </select>

    <!--trim标签条件查询用户-->
    <select id="findUserByCondition3" resultType="User" parameterType="User">
        <include refid="selectUser"></include>
        <trim prefix="where" suffix="order by age" prefixOverrides="and | or" suffixOverrides=",">
            <if test="id!=null and id!=''">
                and id=#{id}
            </if>
            <if test="username!=null and username!=''">
                and username=#{username}
            </if>
        </trim>
    </select>


    <!--查询所有用户,演示pageHelper插件-->
    <select id="findAll" resultType="user">
      select  * from user
    </select>


    <!--set标签更新用户-->
    <update id="updateUser" parameterType="user">
        update user
        <set>
            <if test="username!=null and username!=''">
                username=#{username},
            </if>
            <if test="age!=null and age!=''">
                age=#{age},
            </if>
            <if test="birthday!=null and birthday=''">
                birthday=#{birthday}
            </if>
            where id=#{id}
        </set>
    </update>


</mapper>

2.5 如果想sql语句在控制台打印出来在mybatis核心配置文件中加入

<settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
</settings>

2.6测试文件

public class UserTest {
    private UserMapper userMapper;
    @Before
    public  void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config2");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        userMapper=sqlSession.getMapper(UserMapper.class);

    }
	
	//根据多个id批量查询用户
    @Test
    public void findUsersByIds(){
        List<Integer> integers = new ArrayList<>();
        integers.add(1);
        integers.add(2);
        integers.add(3);
        List<User> users = userMapper.findUsersByIds(integers);
        for (User user : users) {
            System.out.println(user.toString());
        }
    }
}

二、自定义类型转换器typeHandler学习

1、自定义类型转换器typeHandler的原因与步骤:

 Mybatis已经提供了默认的类型处理器,最基本的类型已经有内置的
    可以自己处理不支持的或非标准的类型。具体做法为:实现 org.apache.ibatis.type.TypeHandler 接口, 或继承一个很便利的类 org.apache.ibatis.type.BaseTypeHandler, 然后可以选择性地将它映射到一个JDBC类型。
    开发步骤:
    1、定义转换类继承类BaseTypeHandler<T>
    2、覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法
    3、在MyBatis核心配置文件中进行注册
    4、测试转换是否正确

2、 自定义示例 (将DATE类型的数据转换为时间戳存储到数据库中)

public class MyDateTypeHandler extends BaseTypeHandler<Date> {
		//将Java类型转换为java类型
		@Override
		public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
			//获得时间戳
			long time = parameter.getTime();
			//i 为参数序号
			ps.setLong(i, time);
		}

		//将数据库类型转换为java类型
		//String columnName 要转换的字段名称
		//ResultSet rs查询出的结果集  虚拟机会根据不同的场合调用不同的方法 ,后面三个返回值相同
		@Override
		public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
			//获取结果集中的时间戳数据转换为Date
			long time = rs.getLong(columnName);
			Date date = new Date(time);
			return date;
		}
		//将数据库类型转换为java类型
		@Override
		public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
			long time = rs.getLong(columnIndex);
			Date date = new Date(time);
			return date;
		}
		//将数据库类型转换为java类型
		@Override
		public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
			long time = cs.getLong(columnIndex);
			Date date = new Date(time);
			return date;
		}
	}

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

 <!--配置分页助手插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

三、pageHelper插件的使用

1、在pom.xml导入坐标

<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>0.9.5</version>
    </dependency>

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

<!--配置分页助手插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

3、调用pageHelper

@Test
    public void finAll(){

        //设置分页相关参数,当前页+每页显示条数
        PageHelper.startPage(3,3);
        List<User> all = userMapper.findAll();
        for (User user : all) {
            System.out.println(user.toString());
        }

        //获取分页相关参数
        PageInfo pageInfo=new PageInfo(all);
        System.out.println("当前页:"+pageInfo.getPageNum());
        System.out.println("每页显示条数:"+pageInfo.getPageSize());
        System.out.println("总条数:"+pageInfo.getSize());
        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());
    }

4、分页结果展示

3.1 分页结果展示图

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值