實現自定義註解

1.自定義select in在上一篇介紹了下面介紹其餘的java

2.自定義update Bean註解數據庫

在擴展update註解時,數據庫每張表的字段和實體類的字段必須遵循一個約定(數據庫中採用下劃線命名法,實體類中採用駝峯命名法)。當咱們update的時候,會根據每一個字段的映射關係,寫出以下代碼:app

<update id="updateUsersById" parameterType="com.lucifer.bean.User">
    UPDATE users
        <set>
        <if test=「userName != null">
            user_name = #{userName} ,
        </if>
        <if test=「password != null">
            password = #{password} ,
        </if>
        <if test=「phone != null">
            phone = #{phone},
        </if>
        <if test=「email != null">
            email = #{email},
        </if>
        <if test=「address != null">
            address = #{address},
        </if>
        <if test="gmtCreated != null">
            gmt_created = #{gmtCreated},
        </if>
        <if test="gmtModified != null">
            gmt_modified = #{gmtModified},
        </if>
    </set>
    WHERE id = #{id}
</update> 

咱們能夠將實體類中的駝峯式代碼轉換爲下劃線式命名方式,這樣就能夠將這種映射規律自動化 
通過實現LanguageDriver後,註解代碼爲
ide

@Update("UPDATE users (#{user}) WHERE id = #{id}")
@Lang(SimpleUpdateLangDriver.class)
void updateUsersById(User user);

相對於原始的代碼量有很大的減小,而且,一個類中字段越多,改善也就越明顯。實現方式爲:ui

public class SimpleUpdateLangDriver extends XMLLanguageDriver implements LanguageDriver{

    private final Pattern inPattern = Pattern.compile("\\(#\\{(\\w+)\\}\\)");

    @Override
    public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
        Matcher matcher = inPattern.matcher(script);
        if (matcher.find()) {
            StringBuilder sb = new StringBuilder();
            sb.append("<set>");

            for (Field field : parameterType.getDeclaredFields()) {
                String tmp = "<if test=\"_field != null\">_column=#{_field},</if>";
                sb.append(tmp.replaceAll("_field", field.getName()).replaceAll("_column",
                        CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName())));
            }

            sb.deleteCharAt(sb.lastIndexOf(","));
            sb.append("</set>");

            script = matcher.replaceAll(sb.toString());
            script = "<script>" + script + "</script>";
        }

        return super.createSqlSource(configuration, script, parameterType);
    }
}

Update的實現能知足大部分的業務,但有些業務場景能夠會遇到根據查詢條件來更新查詢參數的狀況,好比Update uesrs SET uesr_name = ‘tom’ WHERE user_name = ‘Jack’; 在這中場景的時候請不要使用自定義的SQL解析器spa

還有查詢和插入自定義.net

http://lib.csdn.net/article/javaee/55848?knId=320(可查看)code

相關文章
相關標籤/搜索