@@ -308,6 +308,75 @@ data class Dst(
308308annotation class ZonedDateTimeConverter (val zoneIdOf : String )
309309```
310310
311+ ##### コンバーターを定義する
312+ コンバーターは` AbstractKConverter<A, S, D> ` を継承して定義します。
313+ ジェネリクス` A ` ,` S ` ,` D ` はそれぞれ以下の意味が有ります。
314+ - ` A ` : コンバートアノテーションの` Type `
315+ - ` S ` : 変換前の` Type `
316+ - ` D ` : 変換後の` Type `
317+
318+ 以下は` java.sql.Timestamp ` から` ZonedDateTime ` へ変換を行うコンバーターの例です。
319+
320+ ``` kotlin
321+ class TimestampToZonedDateTimeConverter (
322+ annotation : ZonedDateTimeConverter
323+ ) : AbstractKConverter<ZonedDateTimeConverter, Timestamp, ZonedDateTime>(annotation) {
324+ private val timeZone = ZoneId .of(annotation.zoneIdOf)
325+
326+ override val srcClass: KClass <Timestamp > = Timestamp ::class
327+
328+ override fun convert (source : Timestamp ): ZonedDateTime = ZonedDateTime .of(source.toLocalDateTime(), timeZone)
329+ }
330+ ```
331+
332+ コンバーターのプライマリコンストラクタの引数はコンバートアノテーションのみ取る必要が有ります。
333+ これは` KMapper ` の初期化時に呼び出されます。
334+
335+ 例の通り、アノテーションに定義した引数は適宜参照することができます。
336+
337+ ##### 付与する
338+ ここまでで定義したコンバートアノテーションとコンバーターをまとめて書くと以下のようになります。
339+ ` InstantToZonedDateTimeConverter ` は` java.time.Instant ` をソースとするコンバーターです。
340+
341+ ``` kotlin
342+ @Target(AnnotationTarget .VALUE_PARAMETER )
343+ @Retention(AnnotationRetention .RUNTIME )
344+ @MustBeDocumented
345+ @KConvertBy([TimestampToZonedDateTimeConverter ::class , InstantToZonedDateTimeConverter ::class ])
346+ annotation class ZonedDateTimeConverter (val zoneIdOf : String )
347+
348+ class TimestampToZonedDateTimeConverter (
349+ annotation : ZonedDateTimeConverter
350+ ) : AbstractKConverter<ZonedDateTimeConverter, Timestamp, ZonedDateTime>(annotation) {
351+ private val timeZone = ZoneId .of(annotation.zoneIdOf)
352+
353+ override val srcClass: KClass <Timestamp > = Timestamp ::class
354+
355+ override fun convert (source : Timestamp ): ZonedDateTime = ZonedDateTime .of(source.toLocalDateTime(), timeZone)
356+ }
357+
358+ class InstantToZonedDateTimeConverter (
359+ annotation : ZonedDateTimeConverter
360+ ) : AbstractKConverter<ZonedDateTimeConverter, Instant, ZonedDateTime>(annotation) {
361+ private val timeZone = ZoneId .of(annotation.zoneIdOf)
362+
363+ override val srcClass: KClass <Instant > = Instant ::class
364+
365+ override fun convert (source : Instant ): ZonedDateTime = ZonedDateTime .ofInstant(source, timeZone)
366+ }
367+ ```
368+
369+ これを付与すると以下のようになります。
370+
371+ ``` kotlin
372+ data class Dst (
373+ @ZonedDateTimeConverter(" Asia/Tokyo" )
374+ val t1 : ZonedDateTime ,
375+ @ZonedDateTimeConverter(" -03:00" )
376+ val t2 : ZonedDateTime
377+ )
378+ ```
379+
311380### マッピング時に用いる引数名・フィールド名の設定
312381` KMapper ` は、デフォルトでは引数名に対応する名前のフィールドをソースからそのまま探します。
313382一方、引数名とソースで違う名前を用いたいという場合も有ります。
0 commit comments