Mybatis第三章--动态sql\分页插件\反向工程
一、动态sql
动态sql是mybatis强大的功能之一,动态sql能大大降低代码的编写数量。
降低工程量。动态sql就是根据不同的条件去拼接sql,实现一个方法,实
现多个功能。
动态sql关键的几个标签:
if、where、trim、choose...when...otherwise、foreach
Ⅰ、if标签
<select id="findByConditionWithIf" resultType="com.ykq.entity.Account">
select * from account where 1=1
<if test="name!=null and name!=''">
and name like concat('%',#{name},'%')
</if>
<if test="isdeleted!=null">
and isdeleted=#{isdeleted}
</if>
</select>
if标签中*test*关键字用来判断条件是否成立,如果成立,就将if标签中
的sql语句拼接到执行sql中。但是只有if标签有一些不便,我们可以看*where*
关键字后必须加上*1=1*,这样才能保证if标签中的*and*和*where*拼接成功。
当然,肯定有解决办法。接下来看where标签
Ⅱ、where标签
where标签和 if 标签一块使用举例
<select id="findByConditionWithIf" resultType="com.ykq.entity.Account">
select * from account
<where>
<if test="name!=null and name!=''">
and name like concat('%',#{name},'%')
</if>
<if test="isdeleted!=null">
and isdeleted=#{isdeleted}
</if>
</where>
</select>
where标签的作用:如果where标签中的语句有符合条件的,就会在sql中
加上where关键字,如果if拼接的语句有and或者or直接和where相邻,就会将
and或者or删除
Ⅲ、choose标签
choos标签有两个子标签,when标签和otherwise标签。简单理解,when相当于
switch语句中的case,otherwise标签相当于default。when标签默认执行一个
break,所以只会拼接上一个when里边的sql语句
<select id="findByConditionWithChoose" resultType="com.ykq.entity.Account">
select * from account
<where>
<choose>
<when test="name!=null and name!=''">
and name like concat('%',#{name},'%')
</when>
<when test="isdeleted!=null">
and isdeleted=#{isdeleted}
</when>
<otherwise>
<![CDATA[and money <1000 ]]>
</otherwise>
</choose>
</where>
</select>
Ⅲ、trim标签
trim标签的作用:trim会用指定的内容去替换符合条件的内容,以下是属性
介绍:
prefix:语句的前缀
prefixOverrides:prefix中的内容要替代的内容
suffix:语句的后缀
suffixOverrides:suffix中的内容要替代的内容
<select id="findByConditionWithChoose" resultType="com.ykq.entity.Account">
select * from account
<trim prefix="where" prefixOverrides="or|and" >
<choose>
<when test="name!=null and name!=''">
and name like concat('%',#{name},'%')
</when>
<when test="isdeleted!=null">
and isdeleted=#{isdeleted}
</when>
<otherwise>
<![CDATA[or money <1000 ]]>
</otherwise>
</choose>
</trim>
</select>
当拼接的sql语句开头是and或者or时,使用where替换
Ⅲ、foreach标签
foreach标签能够对一个数据集合进行遍历,循环拼接到sql语句中。但是只
能是list\set\map集合
dao层的方法:
public List<Account> selectss(@Param("ids") List<Integer> ids);
<select id="selectss" resultType="com.fy.bbb.entity.Account">
select * from account
<if test="ids!=null">
<where>
id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</where>
</if>
</select>
foreach中的collection属性值对应方法中传的参数名,item属性值是每次
遍历出来的集合中的一个值,separator属性值语句item的分割,open和close
是开头和结尾处的内容
二、pageHelper分页插件
配置过程:
Ⅰ、在项目中添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
Ⅱ、配置拦截器
在mybatis的配置文件中配置拦截器插件.
详情请见官网链接: [link](https://pagehelper.github.io/docs/howtouse/).
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
Ⅲ、测试代码
PageHelper.startPage()以下的代码在开发环境中放在业务层
public class DemoFenYe {
public static void main(String[] args) throws Exception {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = build.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
PageHelper.startPage(1,2);
List<Account> all = mapper.findAll();
System.out.println(all);
PageInfo allPageInfo = new PageInfo(all);
System.out.println(allPageInfo);
System.out.println(allPageInfo.getList());
}
}
1、PageHelper.startPage(param1,param2);该方法用来开启分页查询,要在查询
方法执行之前开启,第一个参数控制页数,第二个参数控制每页上的数量。
2、PageInfo对象用来包装查出来的结果,PageInfo提供操作数据的各种方法
3、分页查询会自动查询总数
三、反向工程
什么是反向工程?
根据数据库中的表的字段信息,生成项目中的dao层、
entity层、mappe.xml层。使得代码开发人员专注于业务
的实现。
使用步骤:
官网地址:http://mybatis.org/generator/
主要看三个目录:
①Quick Start Guide 看这个导入依赖
②XML Configuration Reference 看这个配置配置文件
③Running Mybatis Generator 看这个找到执行代码
Ⅰ、引入依赖包
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
Ⅱ、引入配置文件
配置文件在项目中和pom.xml同级
gengerator.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动jar的绝对路径,本地仓库中的-->
<classPathEntry location="D:\\aaamaven\\mavenhome\\mysql\\mysql-connector-java\\5.1.26\\mysql-connector-java-5.1.26.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<!--设置生成的文件中没有注解-->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql:///test"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 实体类生成路径-->
<javaModelGenerator targetPackage="com.fy.entity" targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 映射文件生成的路径-->
<sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- dao层生成的路径-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.fy.dao" targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 如果要生成多个表的内容,就要写多个table-->
<table schema="mybatis" tableName="account" domainObjectName="Account" enableUpdateByExample="false" enableSelectByExample="false" enableDeleteByExample="false"
enableCountByExample="false">
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="mysql" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table>
</context>
</generatorConfiguration>
Ⅲ、生成代码
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
Ⅳ、使用过程中出现的错误
问题描述:
当第一遍生成完了之后,第二遍生成时,每一个
文件中都有重复的内容。
解决:
第一:每次生成之前都要将原来生成的文件彻底删除
第二:依赖包的版本不要使用4.版本的