hibernate - Kotlin with JPA: default constructor hell -
as jpa requires, @entity
classes should have default (non-arg) constructor instantiate objects when retrieving them database.
in kotlin, properties convenient declare within primary constructor, in following example:
class person(val name: string, val age: int) { /* ... */ }
but when non-arg constructor declared secondary 1 requires values primary constructor passed, valid values needed them, here:
@entity class person(val name: string, val age: int) { private constructor(): this("", 0) }
in case when properties have more complex type string
, int
, they're non-nullable, looks totally bad provide values them, when there's code in primary constructor , init
blocks , when parameters actively used -- when they're reassigned through reflection of code going executed again.
moreover, val
-properties cannot reassigned after constructor executes, immutability lost.
so question is: how can kotlin code adapted work jpa without code duplication, choosing "magic" initial values , loss of immutability?
p.s. true hibernate aside of jpa can construct objects no default constructor?
as of kotlin 1.0.6, kotlin-noarg
compiler plugin generates synthetic default construtors classes have been annotated selected annotations.
if use gradle, applying kotlin-jpa
plugin enough generate default constructors classes annotated @entity
:
buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version" } } apply plugin: "kotlin-jpa"
for maven:
<plugin> <artifactid>kotlin-maven-plugin</artifactid> <groupid>org.jetbrains.kotlin</groupid> <version>${kotlin.version}</version> <configuration> <compilerplugins> <plugin>jpa</plugin> </compilerplugins> </configuration> <dependencies> <dependency> <groupid>org.jetbrains.kotlin</groupid> <artifactid>kotlin-maven-noarg</artifactid> <version>${kotlin.version}</version> </dependency> </dependencies> </plugin>
Comments
Post a Comment