zoukankan      html  css  js  c++  java
  • Mybatis学习2

    一、动态sql语句

      一般分页列表上方会有导航栏,任意选择部分条件可查询到对应的信息。Mybatis处理这类动态语句的方法如下。

    if标签与jstl相似,可以根据传过来的值判断该值是否要加入查询条件中。需要注意的是:1.属性自动解析,不用#{}格式,2.逻辑与运算用and代替,逻辑或用or 或者|

    where标签:用于处理动态查询,它的作用是判断标签内的语句是否以 and 为前缀,如果有则删掉,然后补充前缀 where

    <select id="queryByWhere2" resultType="com.zhiyou100.cyf.bean.User">
            select * from user
            <where>
                <if test="username!=null and username!=''">
                    username=#{username}
                </if>
                <if test="sex!=null and sex!=''">
                    and sex=#{sex}
                </if>
            </where>
        </select>

    set标签:用于动态更新,当图片等元素不修改上传空值时可以用此标签。它的作用是判断标签内的语句是否以 , 为后缀,如果有则删掉,然后补充前缀 set

    <update id="updateUser">
            update user 
            <set>
                <if test="username!=null and username!=''">
                    username=#{username},
                </if>
                <if test="sex!=null and sex!=''">
                    sex=#{sex},
                </if>
                <if test="address!=null and address!=''">
                    address=#{address}
                </if>
                where id=#{id}
            </set>
        </update>

    choose标签:类似于switch语句。trim标签:更加灵活,属性prefixOverrides和suffixOverrides分别表示语句前缀和后缀删除相符的字符串,prefix和suffix表示再添加前缀和后缀为该字符串

    <select id="queryByChoose" resultType="com.zhiyou100.cyf.bean.User">
            select <include refid="cols" /> from user 
            <trim prefix="where" prefixOverrides="and">
                <choose>
                    <when test="id!=0">
                        id=#{id}
                    </when>
                    <when test="username!=null and username!=''">
                        and username=#{username}
                    </when>
                    <otherwise>
                        and sex=#{sex}
                    </otherwise>
                </choose>
            </trim>
        </select>

    forEach标签:可用于动态的批量删除,collection属性值为传过来的list集合(名字默认为list),open循环体前缀,close循环体后缀,separator循环间插入的字符串,item表示每个

    集合内元素。下面语句当集合为空时出错。

    <delete id="deleteByIds" parameterType="list">
            delete from user 
            <where>
            <foreach collection="ids" open="id in(" close=")" separator="," item="id">
                #{id}
            </foreach>
            </where>
        </delete>

    二、Mybatis的逆向工程(generator),官方插件,可以自动编写表的实体类、接口和映射文件

    见官网 http://www.mybatis.org/generator/index.html

      1.一般在根目录或源文件夹下创建generator.xml,内容见官网

    <generatorConfiguration>
        <properties resource="db.properties" />
    
        <!-- 数据库的jar包位置 -->
        <classPathEntry
            location="./lib/mysql-connector-java-5.1.47.jar" />
        <!-- 配置连接数据库信息 -->
        <context id="DB2Tables" targetRuntime="MyBatis3">
            <!-- 禁止所有注释 -->
            <commentGenerator>
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <jdbcConnection driverClass="${driver}"
                connectionURL="${url}" userId="${username}" password="${password}">
            </jdbcConnection>
    
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
            <!-- 实体类所在包位置 -->
            <javaModelGenerator
                targetPackage="com.zhiyou100.cyf.bean" targetProject="./src">
                <property name="enableSubPackages" value="true" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
            <!-- 映射文件所在包位置 -->
            <sqlMapGenerator
                targetPackage="com.zhiyou100.cyf.mapper" targetProject="./resources">
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
            <!-- 接口所在包位置 -->
            <javaClientGenerator type="XMLMAPPER"
                targetPackage="com.zhiyou100.cyf.dao" targetProject="./src">
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
            <!-- schema:数据库名 tableName:表名 domainObjectName:实体类名 可以将提供的example 设置为false 
                多个表建立多个table标签 -->
            <table schema="mybatis" tableName="user" domainObjectName="User"
                enableCountByExample="false" enableDeleteByExample="false"
                enableSelectByExample="fales" enableUpdateByExample="false">
                <property name="useActualColumnNames" value="true" />
                <generatedKey column="ID" sqlStatement="DB2"
                    identity="true" />
                <columnOverride column="DATE_FIELD"
                    property="startDate" />
                <ignoreColumn column="FRED" />
                <columnOverride column="LONG_VARCHAR_FIELD"
                    jdbcType="VARCHAR" />
                    <!-- 实体类名更改 -->
                <columnOverride column="u_createtime" property="uCreateTime" />
            </table>
        </context>
    </generatorConfiguration>

      2.导入jar包 mybatis-generator-core-1.3.5.jar,导入mybatis所需的包和配置文件

      3.创建一个测试类,主方法运行以下代码

    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);

     在配置文件加入映射文件路径,基本告成。

    三、使用PageHelper完成分页查询,参考官网https://github.com/pagehelper/Mybatis-PageHelper

      1.导入jar包  pagehelper-x.y.z.jar and jsqlparser-x.y.z.jar  注意很可能出现不兼容问题。这里使用 pagehelper-5.1.10.jar 和 jsqlparser-2.0.jar

      2.配置PageHelper

    <properties resource="db.properties" /><!--注意plugins标签的位置 -->
        <plugins>
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!-- config params as the following -->
                <property name="param1" value="value1" />
            </plugin>
        </plugins>
        <environments default="development">

      3.使用,这里使用PageInfo用法

    在映射文件和dao中创建查询所有信息的方法,然后在测试类中

    @Test
        void testSelectAll() {
            int pageNum=1;
            int pageSize=3;
            PageHelper.startPage(pageNum, pageSize);
            List<User> list=um.selectAll();
            PageInfo<User> page=new PageInfo<>(list);
            System.out.println(page.getList());
        }

     这里一个page对象的具体显示内容如下

     
    PageInfo{pageNum=3, 
    pageSize=3, //每页记录数
    size=2, //该页实际记录数
    startRow=7, //sql起始行
    endRow=8,//sql结束行
    total=8, //总记录数
    pages=3,   //总页数
    list=Page{count=true, pageNum=3, pageSize=3, startRow=6, endRow=9, total=8, pages=3, reasonable=false, pageSizeZero=false}//起始行和结束行数据暂不清楚
    [User [id=7, username=付栓, sex=男, birthday=Tue Aug 06 00:00:00 CST 2019, address=的无缝无法], User [id=8, username=建国, sex=男, birthday=Thu Aug 29 00:00:00 CST 2019, address=非法围绕]],
    prePage=2, //上一页页码
    nextPage=0, //下一页页码
    isFirstPage=false, //是否为第一页
    isLastPage=true, //是否为末页
    hasPreviousPage=true, //是否有上一页
    hasNextPage=false,//是否有下一页
    navigatePages=8, //该页的导航页码个数
    navigateFirstPage=1,//导航页码首页码
    navigateLastPage=3, //导航页码末页码
    navigatepageNums=[1, 2, 3]}//该页所有导航页码的数组
     

    想要获取结果集合调用page.getList()方法,page中包含了获取上述属性的方法,设置导航页码个数用set方法无效,需要在构造函数中设置

    PageInfo<User> page=new PageInfo<>(list,10);//设置导航页码个数为10
     
  • 相关阅读:
    「APIO2017」商旅
    【CQOI2017】小Q的表格
    【HNOI2016】树
    【NOI2018模拟】Yja
    测试
    Loj #6073.「2017 山东一轮集训 Day5」距离
    「AHOI / HNOI2017」影魔
    Loj 6068. 「2017 山东一轮集训 Day4」棋盘
    【SDOI2014】向量集
    远程服务器安装nginx
  • 原文地址:https://www.cnblogs.com/psxfd4/p/11437504.html
Copyright © 2011-2022 走看看