V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
mikicomo
V2EX  ›  问与答

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

  •  1
     
  •   mikicomo · May 4, 2020 · 883 views
    This topic created in 2184 days ago, the information mentioned may be changed or developed.

    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}这样的只是个占位符,并不能直接获取入参进行注入

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5304 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 09:38 · PVG 17:38 · LAX 02:38 · JFK 05:38
    ♥ Do have faith in what you're doing.