龙哥网

龙哥网

Mybatis如何自动生成sql语句_java(mybatis自定义sql语句)
2022-03-01

目录
  • Mybatis自动生成sql语句
  • Mybatis的动态sql语句
    • if标签的使用
    • where标签的使用
    • foreach标签的使用
    • sql语句的简化编写

Mybatis自动生成sql语句

创建maven项目,将该配置文件运行即可生成 sql 语句

<?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">
<!-- MyBatis 自动生成sql代码  -->
<generatorConfiguration>
    <!-- 导入jar包(路径) -->
    <classPathEntry location="E:\CourseWare\MYSQL\mysql-connector-java-5.1.26-bin.jar" />
    <!-- 设置生成代码的规则 targetRuntime 开发环境使用Mybatis3的版本 -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"></plugin>
        <commentGenerator>
            <!-- 这个元素用来去除指定生成的注释中是否包含生成的日期 false:表示保护 -->
            <!-- 如果生成日期,会造成即使修改一个字段,整个实体类所有属性都会发生变化,不利于版本控制,所以设置为true -->
            <property name="suppressDate" value="true" />
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="false" />
        </commentGenerator>
        <!-- 连接数据库的四要素 -->
        <jdbcConnection 
            driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/user" 
            userId="root"
            password="root">
        </jdbcConnection>
        <!-- 该属性用于指定MyBatis生成器是否应该强制使用java.math。小数点和数字域的BigDecimal -->   
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 定义实体类 bean -->
        <javaModelGenerator targetPackage="en.et.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 接口映射的注解 或者xml文件路径 -->
        <sqlMapGenerator targetPackage="cn.et.resource" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成的接口所在的位置 type="xml 或者 注解" -->
        <javaClientGenerator type="ANNOTATEDMAPPER"
            targetPackage="en.et.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 告诉mbg 需要生成代码的数据库的表 -->
        <table tableName="emp"></table>
    </context>
</generatorConfiguration>

Mybatis的动态sql语句

Mybatis的动态sql语句主要解决的问题是不同条件sql语句的拼接。

例如:根据用户信息,查询用户列表,当不知道根据的是用户的什么信息时,写出查询的SQL语句是有一定困难的,而动态SQL语句主要解决的就是此类问题。

if标签的使用

在持久层接口定义方法

    /**
     * 根据用户信息,查询用户列表
     * @param user
     * @return
     */
    List<User> findByUser(User user);

编写持久层接口对应的映射文件

 <!-- 根据用户信息,查询用户列表 -->
    <select id="findByUser" resultType="User" parameterType="User">
        select *from user where 1 = 1
        <if test="id != 0">
            and id = #{id}
        </if>
        <if test="username != null and username != '' ">
            and username like #{username}
        </if>
        <if test="birthday != null">
            and birthday = #{birthday}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
        <if test="address != null">
            and address = #{address}
        </if>
    </select>

编写测试方法

  /**
     * 根据用户信息,查询用户列表
     */
    @Test
    public void testFindByUser()
    {
        User user = new User();
        user.setUsername("%王%");
        List<User> users = userDao.findByUser(user);
        for (User u : users)
        {
            System.out.println(u);
        }
    }

where标签的使用

为了简化上面 where 1=1 的条件拼接,我们可以采用标签来简化开发,因此修改持久层映射文件

 <!-- 根据用户信息,查询用户列表 -->
    <select id="findByUser" resultType="User" parameterType="User">
        select *from user
        <where>
            <if test="id != 0">
                and id = #{id}
            </if>
            <if test="username != null and username != '' ">
                and username like #{username}
            </if>
            <if test="birthday != null">
                and birthday = #{birthday}
            </if>
            <if test="sex != null">
                and sex = #{sex}
            </if>
            <if test="address != null">
                and address = #{address}
            </if>
        </where>
    </select>

foreach标签的使用

froeach是对一个集合进行遍历,通常在构建in条件语句的时候应用

例如:根据一个用户id集合查询用户。

对id集合进行封装,加入到List集合

编写持久层接口方法

  /**
     * 根据id集合查询用户
     * @param queryUR
     * @return
     */
    List<User> findInIds(QueryUR queryUR);

编写持久层接口映射文件

  <!--根据id集合查询用户 -->
    <select id="findInIds" resultType="user" parameterType="int">
       select *from user
       <where>
           <if test="ids != null and ids.size() > 0">
                <!-- foreach:用于遍历集合
                    collection:代表要遍历的集合
                    open:代表语句的开始部分
                    close:代表语句的结束部分
                    item:代表需要遍历的集合的每个元素
                    sperator:代表分隔符
                 -->
               <foreach collection="ids" open="id in (" close=")" item="uid" separator=",">
                    #{uid}
               </foreach>
           </if>
       </where>
    </select>

编写测试方法

  /**
     * 根据id集合查询用户
     */
    @Test
    public void testFindInIds()
    {
        QueryUR queryUR = new QueryUR();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(41);
        ids.add(43);
        ids.add(45);
        queryUR.setIds(ids);
        List<User> users = userDao.findInIds(queryUR);
        for (User user : users)
        {
            System.out.println(user);
        }
    }

sql语句的简化编写

在映射文件中,可以将重复的sql语句通过sql标签提取出来,使用include标签引用即可,已达到sql重用的效果。如下所示:

    <!--抽取重复的语句代码片段-->
    <sql id="querySql">
        select *from user
    </sql>
    <select id="findAll" resultType="USER" >
        <include refid="querySql"></include>
    </select>
    <!--根据id查询用户-->
    <select id="findById" resultType="User" parameterType="int">
        <include refid="querySql"></include> where id= #{userID};
    </select>
免责声明
本站部分资源来源于互联网 如有侵权 请联系站长删除
龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。