MyBatis 动态SQL查询,多条件,分页

<?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="cn.bdqn.mybatis.mapper.CameraMapper">
<!-- 关键是where部分,得根据条件的有效性进行判断   使用where标签动态做-->
	<select id="findCamera" resultType="Camera">
		SELECT
			id,
			typeId,
			brandId,
			title,
			pixel,
			zoom,
			price,
			color
		FROM Camera
		<where>
			<if test="typeId!=null">typeId=#{typeId}</if>
			
			<if test="brandId!=null">and brandId=#{brandId}</if>
			<!-- 由于标签就是由<>组成的,在xml文件中是具有特殊含义的字符,在解析xml时发生错误,解析器xmlcdata块中是普通的字符 -->
			<if test="pixel!=null"><![CDATA[and pixel>=#{pixel}]]></if>
			<if test="zoom!=null"><![CDATA[and zoom>=#{zoom}]]></if>
			<if test="price!=null"><![CDATA[and price<=#{price}]]></if>
			<if test="color!=null">and color like #{color}</if>
			<if test="title!=null">and title like #{title}</if>
		</where>
		ORDER BY id
	
	</select>
</mapper>
package cn.bdqn.mybatis.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import cn.bdqn.mybatis.entity.Camera;
import cn.bdqn.mybatis.entity.Grade;
import cn.bdqn.mybatis.entity.User;

//通过接口里边的抽象方法来调用对应的语句
//接口对应映射文件----把SQL语句的命名空间设置成接口的完整类名


//相当于原来dao层,我只需要定义dao接口,那具体的实现类现在不用咱自己写了,只需拿到mapper接口类即可   省了很多事,提高开发效率
public interface CameraMapper {
	
	 //根据条件搜索,mybatis不会自动识别我要对应到哪个属性上,需要添加注解
	public List<Camera> findCamera(
			@Param("typeId") Long typeId,
			@Param("brandId") Long brandId,
			@Param("pixel") Integer pixel,
			@Param("zoom") Double zoom,
			@Param("price") Double price,
			@Param("color") String color,
			@Param("title") String title
			);

}

mybatis自带的分页机制不推荐使用:首先会用sql语句,把数据库中所有数据加载回内存,再用我指定的页号、每页行数在内存中把那一页的数据提取出来。效率差。

更好的分页,在查询的时候,把我想看的分页语句只显示出来。自己手写底层分页语句。借助插件机制,自己写一个分页插件(可能公司有自己的分页插件)

第一步:添加分页插件

 mybatis的特点就是专注于执行语句的效率

在配置文件中,环境上边配置插件

<plugins>  
	  <plugin interceptor="cn.bdqn.mybatis.plugin.PaginationInterceptor">
	    	<property name="dialectClass" value="cn.bdqn.mybatis.plugin.MySQLDialect"/>    //分页插件支持两种方言类  oracle和mysql
	  </plugin>  
</plugins>
public List<Camera> findCamera(
              //cn.bdqn.mybatis.plugin.中存在PageParam这个类 @Param("pageParam") PageParam param, 名字必须叫"pageParam" @Param("typeId") Long typeId, @Param("brandId") Long brandId, @Param("pixel") Integer pixel, @Param("zoom") Double zoom, @Param("price") Double price, @Param("color") String color, @Param("title") String title );
原文地址:https://www.cnblogs.com/Angelinas/p/5629656.html