V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
mikicomo
V2EX  ›  问与答

使用 mybatis 的 SQL 构造器 手动构造 SQL,参数替换有什么好方法做吗?

  •  1
     
  •   mikicomo · 2020-05-04 15:07:53 +08:00 · 730 次点击
    这是一个创建于 1957 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://mybatis.org/mybatis-3/zh/statement-builders.html#

    // 动态条件(注意参数需要使用 final 修饰,以便匿名内部类对它们进行访问)
    public String selectPersonLike(final String id, final String firstName, final String lastName) {
      return new SQL() {{
        SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");
        FROM("PERSON P");
        if (id != null) {
          WHERE("P.ID like #{id}");
        }
        if (firstName != null) {
          WHERE("P.FIRST_NAME like #{firstName}");
        }
        if (lastName != null) {
          WHERE("P.LAST_NAME like #{lastName}");
        }
        ORDER_BY("P.LAST_NAME");
      }}.toString();
    }
    

    我希望通过这种方式,构造出 sql,传递给另一个服务,他会把我的 sql 当做子查询条件进行查询

    但是这样的话,当遇到参数是日期类型时,有什么好的办法吗?只能手动把日期格式化为 String 类型进行拼接吗?

    他 demo 中给出的#{firstName}这样的只是个占位符,并不能直接获取入参进行注入

    目前尚无回复
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2857 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 06:03 · PVG 14:03 · LAX 23:03 · JFK 02:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.