Created
January 17, 2025 03:17
-
-
Save antop-dev/7714ea56d6d43f1ae0010acdc0f5d83c to your computer and use it in GitHub Desktop.
Exposed MariDB(MySQL) JSON 컬럼과 Set<String> 타입일 매핑하기
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package org.antop.board.common.exposed | |
| import kotlinx.serialization.encodeToString | |
| import kotlinx.serialization.json.Json | |
| import org.jetbrains.exposed.sql.Column | |
| import org.jetbrains.exposed.sql.ColumnType | |
| import org.jetbrains.exposed.sql.Table | |
| /** | |
| * Set<String> ↔︎ JSON 타입 매핑 (내부는 []) | |
| */ | |
| class JsonArrayColumnType : ColumnType<Set<String>>() { | |
| override fun sqlType(): String = "longtext" | |
| override fun valueFromDB(value: Any): Set<String> = | |
| when (value) { | |
| is String -> Json.decodeFromString<Set<String>>(value) | |
| else -> setOf() | |
| } | |
| override fun notNullValueToDB(value: Set<String>): Any = nonNullValueToString(value) | |
| override fun nonNullValueToString(value: Set<String>): String = Json.encodeToString(value) | |
| } | |
| fun Table.jsonArray(name: String): Column<Set<String>> = registerColumn(name, JsonArrayColumnType()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.jetbrains.exposed.sql.Expression | |
| import org.jetbrains.exposed.sql.ExpressionWithColumnType | |
| import org.jetbrains.exposed.sql.Op | |
| import org.jetbrains.exposed.sql.QueryBuilder | |
| import org.jetbrains.exposed.sql.stringParam | |
| /** | |
| * JSON_CONTAINS 펑션을 사용하여 검색 쿼리 생성 | |
| * | |
| * WHERE JSON_CONTAINS([expr], 'one', '["[v]"]') | |
| */ | |
| class JsonContainsOp( | |
| private val expr: Expression<*>, | |
| private val v: String, | |
| ) : Op<Boolean>() { | |
| override fun toQueryBuilder(queryBuilder: QueryBuilder) { | |
| val param = stringParam("[\"$v\"]") | |
| queryBuilder { | |
| append("JSON_CONTAINS(") | |
| append(expr) | |
| append(", ") | |
| append(param) | |
| append(")") | |
| } | |
| } | |
| } | |
| infix fun <T> ExpressionWithColumnType<T>.jsonContains(v: String) = JsonContainsOp(this, v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment