|
| 1 | +## Value Class |
| 2 | + |
| 3 | +엔티티의 프로퍼티를 kotlin의 [`value class`](https://kotlinlang.org/docs/inline-classes.html)로 선언할 수 있습니다. |
| 4 | + |
| 5 | +```kotlin |
| 6 | +@Entity |
| 7 | +class User( |
| 8 | + @Id |
| 9 | + @GeneratedValue(strategy = GenerationType.AUTO) |
| 10 | + val id: UserId = UserId(0), |
| 11 | +) |
| 12 | + |
| 13 | +@JvmInline |
| 14 | +value class UserId(private val value: Long) |
| 15 | + |
| 16 | +``` |
| 17 | + |
| 18 | +hibernate를 사용해 Kotlin JDSL을 통해 조회 시 에러가 발생합니다. |
| 19 | + |
| 20 | +```kotlin |
| 21 | +@Service |
| 22 | +class UserService( |
| 23 | + private val jpqlRenderContext: JpqlRenderContext, |
| 24 | + private val entityManager: EntityManager, |
| 25 | +) { |
| 26 | + |
| 27 | + fun findById(userId: UserId): User? { |
| 28 | + val query = jpql { |
| 29 | + select( |
| 30 | + entity(User::class) |
| 31 | + ).from( |
| 32 | + entity(User::class), |
| 33 | + ).where( |
| 34 | + path(User::id).equal(userId) // 에러 발생 지점 |
| 35 | + ) |
| 36 | + } |
| 37 | + |
| 38 | + return entityManager.createQuery(query, jpqlRenderContext).apply { maxResults = 1 }.resultList.firstOrNull() |
| 39 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +``` |
| 44 | +org.hibernate.type.descriptor.java.CoercionException: Cannot coerce value 'UserId(value=1)' [com.example.entity.UserId] to Long |
| 45 | +... |
| 46 | +``` |
| 47 | + |
| 48 | +이를 해결하려면 Kotlin JDSL이 매개 변수로 전달되는 `value class`의 unboxing이 필요합니다. |
| 49 | +unboxing은 다음 방안 중 하나를 선택해서 수행할 수 있습니다. |
| 50 | + |
| 51 | +### JpqlValue용 커스텀 JpqlSerializer |
| 52 | + |
| 53 | +에러를 해결하기 위해 `EntityManager`에 인자들을 `value class` 그 자체로 넘기지 않고 unboxing한 값을 넘겨야합니다. |
| 54 | +Kotlin JDSL은 `JpqlValueSerializer` 클래스에서 인자들을 추출하는 역할을 담당합니다. |
| 55 | +따라서 기본 제공하는 클래스 대신 커스텀 Seriailzer를 등록해야 합니다. |
| 56 | + |
| 57 | +먼저 다음과 같은 커스텀 Seriailzer를 생성합니다. |
| 58 | + |
| 59 | +```kotlin |
| 60 | +class CustomJpqlValueSerializer : JpqlSerializer<JpqlValue<*>> { |
| 61 | + override fun handledType(): KClass<JpqlValue<*>> { |
| 62 | + return JpqlValue::class |
| 63 | + } |
| 64 | + |
| 65 | + override fun serialize( |
| 66 | + part: JpqlValue<*>, |
| 67 | + writer: JpqlWriter, |
| 68 | + context: RenderContext, |
| 69 | + ) { |
| 70 | + val value = part.value |
| 71 | + |
| 72 | + // value class이면 relfection을 사용해 내부 값을 꺼내서 전달 |
| 73 | + if (value::class.isValue) { |
| 74 | + val property = value::class.memberProperties.first() |
| 75 | + val propertyValue = property.getter.call(value) |
| 76 | + |
| 77 | + writer.writeParam(propertyValue) |
| 78 | + return |
| 79 | + } |
| 80 | + |
| 81 | + if (value is KClass<*>) { |
| 82 | + val introspector = context.getValue(JpqlRenderIntrospector) |
| 83 | + val entity = introspector.introspect(value) |
| 84 | + |
| 85 | + writer.write(entity.name) |
| 86 | + } else { |
| 87 | + writer.writeParam(part.value) |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +이제 이 클래스를 `RenderContext`에 추가해야 합니다. |
| 94 | +추가하는 방법은 [다음 문서](custom-dsl.md#serializer)를 참조할 수 있습니다. |
| 95 | +만약 스프링 부트를 사용하는 경우 다음과 같은 코드를 통해 커스텀 Seriziler를 Bean으로 등록하면 됩니다. |
| 96 | + |
| 97 | +```kotlin |
| 98 | +@Configuration |
| 99 | +class CustomJpqlRenderContextConfig { |
| 100 | + @Bean |
| 101 | + fun jpqlSerializer(): JpqlSerializer<*> { |
| 102 | + return CustomJpqlValueSerializer() |
| 103 | + } |
| 104 | +} |
| 105 | +``` |
| 106 | + |
| 107 | +### custom method 사용 |
| 108 | + |
| 109 | +JDSL에서 제공하는 [custom dsl](custom-dsl.md#dsl) 사용해 value class 에 사용되는 매서드를 추가할 수 있습니다. |
| 110 | + |
| 111 | +```kotlin |
| 112 | +class JDSLConfig : Jpql() { |
| 113 | + fun Expressionable<UserId>.equalValue(value: UserId): Predicate { |
| 114 | + return Predicates.equal(this.toExpression(), Expressions.value(value.value)) |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +val query = jpql(JDSLConfig) { |
| 119 | + select( |
| 120 | + entity(User::class) |
| 121 | + ).from( |
| 122 | + entity(User::class), |
| 123 | + ).where( |
| 124 | + path(User::id).equalValue(userId) |
| 125 | + ) |
| 126 | +} |
| 127 | +``` |
| 128 | + |
| 129 | +interface 도입과 오버로딩을 통해 다양한 value class에 대응할 수 있습니다. |
| 130 | + |
| 131 | +```kotlin |
| 132 | +interface PrimaryLongId { val value: Long } |
| 133 | + |
| 134 | +value class UserId(override val value: Long) : PrimaryLongId |
| 135 | + |
| 136 | +class JDSLConfig : Jpql() { |
| 137 | + fun <T: PrimaryLongId> Expressionable<T>.equal(value: T): Predicate { |
| 138 | + return Predicates.equal(this.toExpression(), Expressions.value(value.value)) |
| 139 | + } |
| 140 | +} |
| 141 | +``` |
0 commit comments