MyBatis3使用小记

@Mapper
interface UserMapper {

    @Results(id = "userResult", value = [
            @Result(property = "id", column = "id", id = true),
            @Result(property = "enterprisePosition", column = "enterprise_position")
    ])
    @Select("select * from user where id = #{id}")
    User getUserById(Integer id);

    @ResultMap("userResult")
    @SelectProvider(type = UserSqlBuilder.class, method = "buildGetUsersByName")
    List<User> getUsersByName(
            @Param("name") String name,
            @Param("phone") String phone);

    @UpdateProvider(type = UserSqlBuilder.class, method = "buildUpdate")
    int update(User user);

    class UserSqlBuilder {

        String buildGetUsersByName(Map<String, Object> map) {
            String sql = new SQL() {
                {
                    SELECT("*")
                    FROM("user")
                    if (map.get("name") != null) {
                        WHERE("name=#{name}")
                    }
                    if (map.get("phone") != null) {
                        WHERE("phone=#{phone}")
                    }

                }
            }
            println(sql)
            return sql
        }

        String buildUpdate(User user) {
            String sql = new SQL() {
                {
                    //构造块
                    UPDATE("user")
                    if (user.name != null)
                        SET("name=#{name}")
                    if (user.phone != null)
                        SET("phone=#{phone}")
                    WHERE("id=#{id}")
                }
            }
            println(sql)
            return sql
        }
    }

}

是不是可以不用写xml了?以前新建个表要花4步,第一步新建java model,第二步新建接口,第三步新建xml,第四步起别名。。。现在只需要前两步就完事了,多爽!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,503评论 25 709
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,418评论 11 349
  • 想亲
    PearlParis阅读 128评论 0 0
  • 五,项目实战,页面骨架开发 1. 组建拆封 static目录下加入文件css/reset.css,做css格式的重...
    eastbaby阅读 501评论 0 0
  • 第十三回 花蕊面对宁国夫人,亲自呈上一杯茶。“请夫人尝尝我家乡的洞天贡茶,可还要得?” 宁国夫人把那白瓷茶杯接过来...
    文艺污小姐阅读 376评论 0 0