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

猜你喜欢

转载自www.cnblogs.com/psxfd4/p/11437504.html