使用kotlin编写的动态sql生成器,可使用bean直接生成对应表的insert和update的含有占位符的sql,并且提供方法获取sql中使用到的所有参数

    1. package com.example.sql
    2. import java.util.*
    3. import java.util.stream.Collectors
    4. import kotlin.reflect.KProperty0
    5. import kotlin.reflect.KProperty1
    6. import kotlin.reflect.full.findAnnotation
    7. import kotlin.reflect.full.memberProperties
    8. import kotlin.streams.toList
    9. fun <T : Any> addAllNotNullColumn(
    10. bean: T, columns: ArrayList<String>, parameters: ArrayList<Any?>, placeholders: StringJoiner? = null
    11. ) {
    12. addAllColumn(bean, columns, parameters, placeholders) {
    13. !it.isLateinit && it.getter.call(bean) != null && it.findAnnotation<JdbcIgnore>()?.type != JdbcOperateType.UPDATE
    14. }
    15. }
    16. fun <T : Any> addAllColumn(
    17. bean: T,
    18. columns: ArrayList<String>,
    19. parameters: ArrayList<Any?>,
    20. placeholders: StringJoiner? = null,
    21. filter: (it: KProperty1<out T, *>) -> Boolean
    22. ) {
    23. bean::class.memberProperties.filter(filter).forEach {
    24. columns.add(it.name)
    25. parameters.add(it.getter.call(bean))
    26. placeholders?.add("?")
    27. }
    28. }
    29. class SqlCreator<T : Any>(bean: T) {
    30. private val _bean: T = bean
    31. private val tableName: String?
    32. init {
    33. this.tableName = bean::class.simpleName
    34. }
    35. interface ToSql {
    36. fun toSql(): String
    37. fun getParameters(): List<Any?>
    38. }
    39. inner class Insert : ToSql {
    40. private val _columns = arrayListOf<String>()
    41. private val _parameters = arrayListOf<Any?>()
    42. private val _placeholders = StringJoiner(", ")
    43. fun <K : KProperty0<Any>> addInsertColumn(property: K): Insert {
    44. property.getter.call().let { value ->
    45. _columns.add(property.name)
    46. _parameters.add(value)
    47. _placeholders.add("?")
    48. }
    49. return this
    50. }
    51. fun insertAllNotNullColumn(): Insert {
    52. _columns.clear()
    53. addAllNotNullColumn(_bean, _columns, _parameters, _placeholders)
    54. return this
    55. }
    56. override fun toSql(): String {
    57. if (_columns.isEmpty()) {
    58. throw RuntimeException("insert column need not empty")
    59. }
    60. val columnStr = _columns.stream().collect(Collectors.joining(", "))
    61. return "insert into ${tableName}(${columnStr}) values($_placeholders)"
    62. }
    63. override fun getParameters() = _parameters
    64. }
    65. inner class Update : ToSql {
    66. private val _columns = arrayListOf<String>()
    67. private val _whereList = arrayListOf<Where>()
    68. private val _setColumnParameters = arrayListOf<Any?>()
    69. fun updateAllNotNullColumn(): Update {
    70. _columns.clear()
    71. addAllNotNullColumn(_bean, _columns, _setColumnParameters)
    72. return this
    73. }
    74. fun <K : KProperty0<Any>> setColumn(property: K): Update {
    75. property.getter.call().let { value ->
    76. _columns.add(property.name)
    77. _setColumnParameters.add(value)
    78. }
    79. return this
    80. }
    81. fun createWhere(): Where {
    82. val where = Where()
    83. if (_whereList.isEmpty()) {
    84. _whereList.add(where)
    85. }
    86. return where
    87. }
    88. fun and(where: Where): Update {
    89. where.prefix = "and"
    90. _whereList.add(where)
    91. return this
    92. }
    93. fun or(where: Where): Update {
    94. where.prefix = "or"
    95. _whereList.add(where)
    96. return this
    97. }
    98. override fun toSql(): String {
    99. if (_columns.isEmpty()) {
    100. throw RuntimeException("update set column need not empty")
    101. }
    102. val columnStr = _columns.stream().map { "$it = ?" }.collect(Collectors.joining(", "))
    103. var updateSql = "update $tableName set $columnStr"
    104. val wheres = _whereList.filter { it.isNotEmpty() }.toList()
    105. if (wheres.isNotEmpty()) {
    106. var where = wheres[0].toString()
    107. if (wheres.size > 1) {
    108. where = "(${where})"
    109. for (i in 1 until wheres.size) {
    110. val currentWhere = wheres[i]
    111. where += " ${currentWhere.prefix} ($currentWhere)"
    112. }
    113. }
    114. updateSql = "$updateSql where $where"
    115. }
    116. return updateSql
    117. }
    118. override fun getParameters(): List<Any?> {
    119. return arrayListOf<Any?>().apply {
    120. addAll(_setColumnParameters)
    121. addAll(_whereList.stream().filter { it.isNotEmpty() }.flatMap { it.getParameters().stream() }.toList())
    122. }
    123. }
    124. }
    125. }
    126. data class Condition(
    127. val prefix: String,
    128. val suffix: String,
    129. val label: String,
    130. var next: Condition?
    131. ) {
    132. fun hasNext() = next != null
    133. }
    134. class Where {
    135. var prefix = "and"
    136. private lateinit var _first: Condition
    137. private lateinit var last: Condition
    138. private val _parameters = arrayListOf<Any?>()
    139. private fun addCondition(
    140. prefix: String,
    141. suffix: String,
    142. label: String,
    143. value: Any?,
    144. valueSize: Int = 1,
    145. ): Where {
    146. var suffixStr = suffix
    147. if (valueSize == 1) {
    148. suffixStr += " ?"
    149. } else if (valueSize > 1) {
    150. val joiner = StringJoiner(",")
    151. for (i in 1..valueSize) {
    152. joiner.add("?")
    153. }
    154. suffixStr += " ($joiner)"
    155. }
    156. val current = Condition(prefix, suffixStr, label, null)
    157. if (this::_first.isInitialized) {
    158. last.next = current
    159. } else {
    160. _first = current
    161. }
    162. if (valueSize > 0) {
    163. if (value is Collection<Any?>) {
    164. _parameters.addAll(value)
    165. } else {
    166. _parameters.add(value)
    167. }
    168. }
    169. last = current
    170. return this
    171. }
    172. private fun addIsNull(prefix: String, label: String) =
    173. addCondition(prefix, "is null", label, null, 0)
    174. private fun addIsNotNull(prefix: String, label: String) =
    175. addCondition(prefix, "is not null", label, null, 0)
    176. private fun addEqualTo(prefix: String, label: String, value: Any?) =
    177. addCondition(prefix, "=", label, value)
    178. private fun addNotEqualTo(prefix: String, label: String, value: Any?) =
    179. addCondition(prefix, "<>", label, value)
    180. private fun addGreaterThan(prefix: String, label: String, value: Any?) =
    181. addCondition(prefix, ">", label, value)
    182. private fun addGreaterThanOrEqualTo(prefix: String, label: String, value: Any?) =
    183. addCondition(prefix, ">=", label, value)
    184. private fun addLessThan(prefix: String, label: String, value: Any?) = addCondition(prefix, "<", label, value)
    185. private fun addLessThanOrEqualTo(prefix: String, label: String, value: Any?) =
    186. addCondition(prefix, "<=", label, value)
    187. private fun addIn(prefix: String, label: String, value: Any?, valueSize: Int) =
    188. addCondition(prefix, "in", label, value, valueSize)
    189. private fun addNotIn(prefix: String, label: String, value: Any?, valueSize: Int) =
    190. addCondition(prefix, "not in", label, value, valueSize)
    191. fun andIsNull(label: String) = addIsNull("and", label)
    192. fun orIsNull(label: String) = addIsNull("or", label)
    193. fun andIsNotNull(label: String) = addIsNotNull("and", label)
    194. fun orIsNotNull(label: String) = addIsNotNull("or", label)
    195. fun andEqualTo(label: String, value: Any?) = addEqualTo("and", label, value)
    196. fun orEqualTo(label: String, value: Any?) = addEqualTo("or", label, value)
    197. fun andNotEqualTo(label: String, value: Any?) = addNotEqualTo("and", label, value)
    198. fun orNotEqualTo(label: String, value: Any?) = addNotEqualTo("or", label, value)
    199. fun andGreaterThan(label: String, value: Any?) = addGreaterThan("and", label, value)
    200. fun orGreaterThan(label: String, value: Any?) = addGreaterThan("or", label, value)
    201. fun andGreaterThanOrEqualTo(label: String, value: Any?) = addGreaterThanOrEqualTo("and", label, value)
    202. fun orGreaterThanOrEqualTo(label: String, value: Any?) = addGreaterThanOrEqualTo("or", label, value)
    203. fun andLessThan(label: String, value: Any?) = addLessThan("and", label, value)
    204. fun orLessThan(label: String, value: Any?) = addLessThan("or", label, value)
    205. fun andLessThanOrEqualTo(label: String, value: Any?) = addLessThanOrEqualTo("and", label, value)
    206. fun orLessThanOrEqualTo(label: String, value: Any?) = addLessThanOrEqualTo("or", label, value)
    207. fun andIn(label: String, value: Collection<Any?>) = addIn("and", label, value, value.size)
    208. fun orIn(label: String, value: Collection<Any?>) = addIn("or", label, value, value.size)
    209. fun andNotIn(label: String, value: Collection<Any?>) = addNotIn("and", label, value, value.size)
    210. fun orNotIn(label: String, value: Collection<Any?>) = addNotIn("or", label, value, value.size)
    211. override fun toString(): String = toConditionSql()
    212. private fun toConditionSql(): String {
    213. if (this.isEmpty()) {
    214. return ""
    215. }
    216. val joiner = StringJoiner(" ")
    217. var condition = _first
    218. joiner.add("${condition.label} ${condition.suffix}")
    219. while (condition.hasNext()) {
    220. condition = condition.next!!
    221. joiner.add("${condition.prefix} ${condition.label} ${condition.suffix}")
    222. }
    223. return joiner.toString()
    224. }
    225. fun getParameters() = _parameters.toMutableList()
    226. fun isNotEmpty() = !isEmpty()
    227. fun isEmpty() = !this::_first.isInitialized
    228. }
    229. fun main() {
    230. val userInfo = UserInfoDO().apply {
    231. userName = "xiaoliu"
    232. email = "xiaoliu@qq.com"
    233. }
    234. val insertCreator = SqlCreator(userInfo).Insert().insertAllNotNullColumn()
    235. println(insertCreator.toSql())
    236. println(insertCreator.getParameters())
    237. val updateCreator = SqlCreator(userInfo).Update().updateAllNotNullColumn()
    238. updateCreator.createWhere().andEqualTo("id", 1)
    239. updateCreator.or(updateCreator.createWhere().andIsNotNull("user_name"))
    240. updateCreator.and(updateCreator.createWhere().andNotEqualTo("is_enable", false))
    241. println(updateCreator.toSql())
    242. println(updateCreator.getParameters())
    243. }