zoukankan      html  css  js  c++  java
  • tk.mybaits

    如下列举四种方式,但是不止四种哦。

    其中weekend方式需要升级jdk到1.8及以上。

    废话不代码!

    首先定义数据库表映射类:

    public class MybatisDemo {
        private Long id;
        private Long count;
        private String name;
    
        public Long getId() {
            return id;
        }
        public Long getCount() {
            return count;
        }
        public String getName() {
            return name;
        }
    
    //    setter……
    }

    此处省略了数据库表映射和set方法。

    接下来就是实现example查询的几种方式,核心代码如下:

    方式一:普通Example方式(从and方法开始可以实现动态sql拼接)

        Example example = new Example(CandidateBrandEntity.class);
        example
          //.selectProperties("cabId","cabName")
            .and().andEqualTo("cabDeleted",0)
            .andLike("cabName","%d%");
    
        // 排序
        example.orderBy("cabCreatedTime")
            /*.desc()*/
              .orderBy("cabId").desc();
    
        // 获得结果
        List<CandidateBrandEntity> brands = brandEntityMapper.selectByExample(example);

    方式二:Criteria方式(可使用criteria完成动态sql拼接)

    Example example = new Example(MybatisDemo.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andEqualTo("count", 0)
            .andLike("name", "%d%");
    example.orderBy("count")
            //.desc()
            .orderBy("name").desc();
    List<MybatisDemo> demos = mybatisDemoMapper.selectByExample(example);

    方式三:Example.builder 方式(其中where从句中内容可以拿出来进行动态sql拼接)

    Example example = Example.builder(MybatisDemo.class)
            .select("cabId","cabName")
            .where(Sqls.custom().andEqualTo("count", 0)
            .andLike("name", "%d%"))
            .orderByDesc("count","name")
            .build();
    List<MybatisDemo> demos = mybatisDemoMapper.selectByExample(example);

    方式四:Example.builder + Weekend方式,优势:不用输入属性名,避免数据库有变动或输入错误就会出错

    //获得seekendsql
    WeekendSqls<MybatisDemo> sqls = WeekendSqls.<MybatisDemo>custom();
    
    //可进行动态sql拼接
    sqls = sqls.andEqualTo(MybatisDemo::getCount,0).andLike(MybatisDemo::getName,"%d%");
    
    //获得结果
    List<MybatisDemo> demos = mybatisDemoMapper.selectByExample(Example.builder(MybatisDemo.class).where(sqls).orderByDesc("count","name").build());

     摘抄自

    如果有来生,要做一片树叶。 春天恋上枝,炎夏恋上水。 深秋恋上土,东来化作泥。 润物细无声,生生世世恋红尘。
  • 相关阅读:
    git 强制覆盖本地
    .gitignore 配置
    Git fetch和git pull的区别
    时间函数 date strtotime
    page show
    prepare PDO
    Lucene搜索方法总结
    lucene索引日期和数字
    lucene 3.0.2 + 多文件夹微博数据(时间,微博)构建索引
    lucene 使用注意
  • 原文地址:https://www.cnblogs.com/shujiying/p/12796251.html
Copyright © 2011-2022 走看看