Uploaded image for project: 'Spring Data Commons'
  1. Spring Data Commons
  2. DATACMNS-1338

Unable to use secondary @PersistenceConstructor with Kotlin data classes


    • Type: Bug
    • Status: Closed
    • Priority: Minor
    • Resolution: Fixed
    • Affects Version/s: 2.0.7 (Kay SR7), 2.1 M3 (Lovelace)
    • Component/s: Mapping / Conversion
    • Labels:
    • Environment:
      macOS High Sierra, Kotlin 1.2.41, Spring Boot 2.0.2.RELEASE, Mongo Driver 3.6.3


      I'm using Kotlin Data Classes for my entities. This means all properties must be defined in the primary constructor, including properties annotated with @DBRef. This means that by default, even if properties are annotated with @DBRef(lazy = true), they're still eagerly loaded because KotlinClassGeneratingEntityInstantiator.DefaultingKotlinClassInstantiatorAdapter will load the field when trying to instantiate the class.

      I've worked around this like so:

      @Document(collection = "users")
      data class CustomUser(
              @Id var id: String? = null,
              @DBRef(lazy = true)
              var organisations: MutableList<Organisation> = mutableListOf()
      ) {
          constructor(id: String?): this(id, mutableListOf())

      However I now get the error:

      Failed to instantiate my.package.CustomUser using constructor fun <init>(kotlin.String?): my.package.CustomUser with arguments user123,0,null 

      With the causing exception:

      Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.List 

      This is because the parameter array is constructed based off the metadata from the @PersistenceConstructor ("0,null" are the default bitmask and the DefaultConstructorMarker) but the ObjectInstantiator is built using the default constructor as per KotlinClassGeneratingEntityInstantiator#doCreateEntityInstantiator


          Issue Links



              • Assignee:
                mp911de Mark Paluch
                jonesd9 Daniel Jones
                Last updater:
                Mark Paluch
              • Votes:
                0 Vote for this issue
                2 Start watching this issue


                • Created: