Skip to content
This repository has been archived by the owner on Oct 26, 2022. It is now read-only.

关于choose when otherwise的解析逻辑 #7

Closed
chrobin opened this issue Jul 7, 2019 · 3 comments
Closed

关于choose when otherwise的解析逻辑 #7

chrobin opened this issue Jul 7, 2019 · 3 comments
Labels
enhancement New feature or request

Comments

@chrobin
Copy link
Contributor

chrobin commented Jul 7, 2019

在mybatis中,choose...when...otherwise标签意味着从choose块中的when按顺序进行判断,只要有一个when结果为true,则匹配该when块中的语句,如果所有的when都不匹配,则匹配otherwise块中的语句。
因此,在解析choose...when...otherwise标签是否考虑不要将所有的when都解析出来放在块中,而是选第一个when块解析?
例如:

<select id="testChoose">
        SELECT
        name,
        category,
        price
        FROM
        fruits
        <where>
            <choose>
                <when test="name != null">
                    AND name = #{name}
                </when>
                <when test="category == 'banana'">
                    AND category = #{category}
                    <if test="price != null and price !=''">
                        AND price = ${price}
                    </if>
                </when>
                <otherwise>
                    AND category = 'apple'
                </otherwise>
            </choose>
        </where>
    </select>

就解析为:
SELECT name, category,price FROM fruits where name = ?

@hhyo
Copy link
Owner

hhyo commented Jul 8, 2019

目前这个解析是用来做SQL审核的,所以需要知道所有的查询条件,这也是解析结果保留条件注释的原因,同样if标签也会列出所有条件和结果

不过可以考虑加个变量来控制是否按照mybatis的规则来解析

@hhyo hhyo added the enhancement New feature or request label Jul 8, 2019
@chrobin
Copy link
Contributor Author

chrobin commented Jul 8, 2019

是的,最好可以考虑加个变量来控制解析是否按mybatis的规则来。不然,如果xml是下面这样,解析出来的sql可能不符合sql语法。

<select id="testChoose">
        SELECT
        name,
        category,
        price
        FROM
        fruits
        <where>
            <choose>
                <when test="name != null">
                    name = #{name}
                </when>
                <when test="category == 'banana'">
                    category = #{category}
                </when>
                <otherwise>
                    category = 'apple'
                </otherwise>
            </choose>
        </where>
    </select>

解析出来,就会变成:

 SELECT name, category, price FROM fruits where name = ? category = #{category} category = 'apple'

这并不符合sql语法,但实际上,在mybatis运行时,这个xml并不会产生这样的sql

@hhyo hhyo closed this as completed in 4a18abd Aug 25, 2019
@hhyo
Copy link
Owner

hhyo commented Aug 25, 2019

已处理,更新0.1.9即可,调用方法参考

mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True, native=True)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants