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

Unable to use secondary @PersistenceConstructor with Kotlin data classes

    Details

    • 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:
      None
    • Environment:
      macOS High Sierra, Kotlin 1.2.41, Spring Boot 2.0.2.RELEASE, Mongo Driver 3.6.3

      Description

      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")
      @TypeAlias("user")
      data class CustomUser(
              @Id var id: String? = null,
      
              @DBRef(lazy = true)
              var organisations: MutableList<Organisation> = mutableListOf()
      ) {
          @PersistenceConstructor
          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

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                • Created:
                  Updated:
                  Resolved: