溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Mybatis怎么自動生成sql語句

發(fā)布時間:2021-12-15 12:44:15 來源:億速云 閱讀:669 作者:柒染 欄目:開發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)Mybatis怎么自動生成sql語句,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

Mybatis自動生成sql語句

創(chuàng)建maven項(xiàng)目,將該配置文件運(yùn)行即可生成 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>
    <!-- 導(dǎo)入jar包(路徑) -->
    <classPathEntry location="E:\CourseWare\MYSQL\mysql-connector-java-5.1.26-bin.jar" />
    <!-- 設(shè)置生成代碼的規(guī)則 targetRuntime 開發(fā)環(huán)境使用Mybatis3的版本 -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"></plugin>
        <commentGenerator>
            <!-- 這個元素用來去除指定生成的注釋中是否包含生成的日期 false:表示保護(hù) -->
            <!-- 如果生成日期,會造成即使修改一個字段,整個實(shí)體類所有屬性都會發(fā)生變化,不利于版本控制,所以設(shè)置為true -->
            <property name="suppressDate" value="true" />
            <!-- 是否去除自動生成的注釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="false" />
        </commentGenerator>
        <!-- 連接數(shù)據(jù)庫的四要素 -->
        <jdbcConnection 
            driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/user" 
            userId="root"
            password="root">
        </jdbcConnection>
        <!-- 該屬性用于指定MyBatis生成器是否應(yīng)該強(qiáng)制使用java.math。小數(shù)點(diǎn)和數(shù)字域的BigDecimal -->   
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 定義實(shí)體類 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 需要生成代碼的數(shù)據(jù)庫的表 -->
        <table tableName="emp"></table>
    </context>
</generatorConfiguration>

Mybatis的動態(tài)sql語句

Mybatis的動態(tài)sql語句主要解決的問題是不同條件sql語句的拼接。

例如:根據(jù)用戶信息,查詢用戶列表,當(dāng)不知道根據(jù)的是用戶的什么信息時,寫出查詢的SQL語句是有一定困難的,而動態(tài)SQL語句主要解決的就是此類問題。

if標(biāo)簽的使用

在持久層接口定義方法

/**
     * 根據(jù)用戶信息,查詢用戶列表
     * @param user
     * @return
     */
    List<User> findByUser(User user);

編寫持久層接口對應(yīng)的映射文件

 <!-- 根據(jù)用戶信息,查詢用戶列表 -->
    <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>

編寫測試方法

  /**
     * 根據(jù)用戶信息,查詢用戶列表
     */
    @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標(biāo)簽的使用

為了簡化上面 where 1=1 的條件拼接,我們可以采用標(biāo)簽來簡化開發(fā),因此修改持久層映射文件

 <!-- 根據(jù)用戶信息,查詢用戶列表 -->
    <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標(biāo)簽的使用

froeach是對一個集合進(jìn)行遍歷,通常在構(gòu)建in條件語句的時候應(yīng)用

例如:根據(jù)一個用戶id集合查詢用戶。

對id集合進(jìn)行封裝,加入到List集合

Mybatis怎么自動生成sql語句

編寫持久層接口方法

  /**
     * 根據(jù)id集合查詢用戶
     * @param queryUR
     * @return
     */
    List<User> findInIds(QueryUR queryUR);

編寫持久層接口映射文件

  <!--根據(jù)id集合查詢用戶 -->
    <select id="findInIds" resultType="user" parameterType="int">
       select *from user
       <where>
           <if test="ids != null and ids.size() > 0">
                <!-- foreach:用于遍歷集合
                    collection:代表要遍歷的集合
                    open:代表語句的開始部分
                    close:代表語句的結(jié)束部分
                    item:代表需要遍歷的集合的每個元素
                    sperator:代表分隔符
                 -->
               <foreach collection="ids" open="id in (" close=")" item="uid" separator=",">
                    #{uid}
               </foreach>
           </if>
       </where>
    </select>

編寫測試方法

  /**
     * 根據(jù)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語句的簡化編寫

在映射文件中,可以將重復(fù)的sql語句通過sql標(biāo)簽提取出來,使用include標(biāo)簽引用即可,已達(dá)到sql重用的效果。如下所示:

<!--抽取重復(fù)的語句代碼片段-->
    <sql id="querySql">
        select *from user
    </sql>
    <select id="findAll" resultType="USER" >
        <include refid="querySql"></include>
    </select>
    <!--根據(jù)id查詢用戶-->
    <select id="findById" resultType="User" parameterType="int">
        <include refid="querySql"></include> where id= #{userID};
    </select>

上述就是小編為大家分享的Mybatis怎么自動生成sql語句了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI