Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support method for generating dynamic sql on SQL class #2887

Conversation

kazuki43zoo
Copy link
Member

I propose to add following new method for generating dynamic sql on SQL.

  • applyIf (similar <if> element in XML language driver)
  • applyForEach (similar <foreach> element in XML language driver)

In this change, the developer can write dynamic sql using with fluent style as follow:

applyIf

// Generate following SQL if b and c is null
// UPDATE test SET a=#{a} WHERE (id=#{id})
String sqlString = new SQL()
  .UPDATE("test")
  .applyIf(bean::hasA, sql -> sql.SET("a=#{a}"))
  .applyIf(bean::hasB, sql -> sql.SET("b=#{b}"))
  .applyIf(bean::hasC, sql -> sql.SET("c=#{c}"))
  .WHERE("id=#{id}")
  .toString();

applyForEach

// Generate following SQL if beans has two element
// INSERT INTO test (a, b, c) VALUES (#{list[0].a}, #{list[0].b}, #{list[0].c}), (#{list[1].a}, #{list[1].b}, #{list[1].c})
String sqlString = new SQL()
  .INSERT_INTO("test")
  .INTO_COLUMNS("a", "b", "c")
  .applyForEach(beans, (sql, element, index) ->
    sql.INTO_VALUES(
      String.format("#{list[%s].a}", index),
      String.format("#{list[%s].b}", index),
      String.format("#{list[%s].c}", index)
    ).ADD_ROW())
  .toString();

@mybatis/committers WDYT?

@coveralls
Copy link

Coverage Status

coverage: 87.559% (+0.01%) from 87.545% when pulling bc050f2 on kazuki43zoo:add-suport-method-for-generating-dynamic-sql-on-SQL into c060395 on mybatis:master.

@hazendaz
Copy link
Member

hazendaz commented Nov 9, 2023

@harawata Thoughts? LGTM. Forgot about this.

@harawata
Copy link
Member

harawata commented Nov 9, 2023

@hazendaz @kazuki43zoo

Looks handy. Thank you!

@hazendaz
Copy link
Member

hazendaz commented Dec 3, 2023

@kazuki43zoo Can you update the at since? Then feel free to merge it.

@hazendaz
Copy link
Member

merging and fill fix since right after.

@hazendaz hazendaz merged commit f4d1556 into mybatis:master Dec 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants