关于Mybatis动态sql、逆向工程

1.动态sql语句
2.逆向工程(generator)
3.分页助手(pagehelper)
 
一、动态sql语句(查询条件拼接)
1.JDBC中的实现
public List findByActSql(String name,String sex,String hobby){
    String sql="select * from student";
    if(name!=null) {
        sql+="where name='+name+'";
    }
    if(sex!=null) {
        if(name!=null) {
            sql+="and sex='+sex+'";
        }else {
            sql+="where sex+='+sex+'";
        }
    }
    ......
}

2.MyBatis中的实现

要求:查询相应uname,description查询,若name和description为null,则查询所有
<select id="selectByActSql" resultType="com.zhiyou100.yj.bean.Role">
    select * from role
    <if test="uname!=null">
        where uname=#{uname}
    if>
    <if test="description!=null">
        and description=#{description}
    if>
select>

缺陷:第二个条件满足,第一个条件不满足,sql语句出错

方法一:
<select id="selectByActSql" resultType="com.zhiyou100.yj.bean.Role">
    select * from role where 1=1
    <if test="uname!=null">
        and uname=#{uname}
    if>
    <if test="description!=null">
        and description=#{description}
    if>
select>

方法二:

<select id="selectByActSql_1" resultType="com.zhiyou100.yj.bean.Role">
    select * from role
    <where>    
        <if test="uname!=null">
            and uname=#{uname}
        if>
        <if test="description!=null and description!="">    
            and description=#{description}
        if>
    where>
select>




<select id="selectByActSql_2" resultType="com.zhiyou100.yj.bean.Role">
    select * from role
    "where" prefixOverrides="and \ or">
        <if test="uname!=null">
            and uname=#{uname}
        if>
        <if test="description!=null">
            and description=#{description}
        if>
    
select>


"updateByActSql_1" >
    update role
    <set>    
        <if test="uname!=null">
            uname=#{uname},
        if>
        <if test="description!=null">
            description=#{description}
        if>
            where id=#{id}
    set>



"updateByWhere2" >
    update role
    "set" suffixOverrides=",">
        <if test="uname!=null">
            uname=#{uname},
        if>
        <if test="description!=null">
            description=#{description}
        if>
            where id=#{id}
    




1.定义sql片段
"rolePart">
    id,uname,description

2.引入sql片段==>利用标签(可以是单标签)
<select id="selectAll" resultType="com.zhiyou100.yj.bean.Role">
    select "rolePart"> from role
select>



<select id="selectByLike" resultType="com.zhiyou100.yj.bean.Role">
    select * from role
    "where">
        
            "uname!=null">    
                uname like concat('%',#{uname},'%')    
            
            
                description like concat('%',#{description},'%')
            
        
    
select>



1.遍历集合,每次调用方法,导致与数据库多次交互
    public void deleteById(int id);
2.foreach标签遍历
    public void deletebyIds(@param("ids")List ids);    //集合中的元素是对象==>Integer

    <select id="selectByCondition2"   resultType="com.zhiyou100.yj.bean.Role">
        select "AllPart"/> from role
        <if test="ids.size>0">
            <where>
                
                <foreach collection="ids" open="id in ("  close=")" separator="," item="ids">
                    #{ids}
                foreach>
            where>
        if>
    select>
二、MyBatis逆向工程
MyBatis官网  http://www.mybatis.org/generator/index.html
 
1.导入mybatis-generator的jar包
2.创建generator.xml配置文件(由表自动生成dao,bean,mappper.xml文件)    注意:对应xml文件需手动添加到config.xml
"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">


    "C:\\Users\\BirdXtd\\Desktop\\API\\jar包\\mysql-connector-java-5.1.47.jar"/>

    "DB2Tables" targetRuntime="MyBatis3">

    
        "suppressDate" value="true"/>
        "suppressAllComments" value="true"/>
    
  
    "com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/user"
        userId="root"
        password="root">
    
    
    
      "forceBigDecimals" value="false" />
    


    "com.zhiyou100.yj.bean"  targetProject="./src">
        "enableSubPackages" value="true" />
        "trimStrings" value="true" />
    

    "com.zhiyou100.yj.mapper"   targetProject="./resources">
      "enableSubPackages" value="true" />
    

    "XMLMAPPER"  targetPackage="com.zhiyou100.yj.dao"  targetProject="./src">
      "enableSubPackages" value="true" />
    


    "user" tableName="role" domainObjectName="Role"
    enableCountByExample="false" enableSelectByExample="false"  enableUpdateByExample="false" enableDeleteByExample="false">
        
        "useActualColumnNames" value="true"/>
        "ID" sqlStatement="DB2" identity="true" />
        "DATE_FIELD" property="startDate" />
        "FRED" />
        "LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
    

3.运行generator(ctrl+shift+o:快捷导包)

//新建测试类
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class TestGenerator {
    public static void main(String[] args) throws Exception {
        List warnings = new ArrayList();
        boolean overwrite = true;
        File configFile = new File("mybatisGenerator.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);
      }
}
三、mybatis分页助手
1.引入jar包:jsqlparser及pagehelper
2.配置拦截器插件

    
    "com.github.pagehelper.PageInterceptor">
    
        "param1" value="value1"/>
    

3.测试

@Test
    void testSelectAll() {
        //设置分页,当前页码和每页显示的记录数
        int pageNum=1;
        int pageSize=3;
        PageHelper.startPage(pageNum,pageSize);
        //执行sql功能
        List roles = roleDao.selectAll();
        //查询结果封装到pageInfo对象中
        PageInfo pageinfo=new PageInfo<>(roles);
        System.out.println(pageinfo);
      }

    /*问题备注:
    Result Maps collection already contains value for xxxxxx   
    原因:mybatisGenerator生成xml的时候,可能xml的内容不会被覆盖,而是追加到后面,导致xml里面有两份甚至更多的一样的内容,造成重复注入
    解决:在生成xml前,把mapper标签里面的所有标签删除*/

 

转载于:https://www.cnblogs.com/BoxMonster/p/11443388.html

你可能感兴趣的:(java,数据库)