实现自定义注解

1.自定义select in在上一篇介绍了下面介绍其他的

2.自定义update Bean注解

在扩展update注解时,数据库每张表的字段和实体类的字段必须遵循一个约定(数据库中采用下划线命名法,实体类中采用驼峰命名法)。当我们update的时候,会根据每个字段的映射关系,写出如下代码:

<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后,注解代码为

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

相对于原始的代码量有很大的减少,并且,一个类中字段越多,改善也就越明显。实现方式为:

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解析器

还有查询和插入自定义

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

原文地址:https://www.cnblogs.com/G-JF/p/9305787.html