kotlin delegated field is always null when loaded from hibernate

294 Views Asked by At

I'm trying to do something that would be simple as hell in java but kotlin came to make it a nightmare.

interface IChargeableDTO{

    var name: String
    var ref: String
    var priceCents: Int
    var maxInstallments: Int
    var gateway: PaymentGateway
}

@Embeddable
open class ChargeableDTO(
        @field:NotBlank override  var name: String,
        @field:NotBlank override  var ref: String,
        @field:Min(1) override  var priceCents: Int,
        @field:NotNull @field:Min(1) @field:Max(12) override  var maxInstallments: Int = 1,
        @field:NotNull override  var gateway: PaymentGateway) : IChargeableDTO {


@Embeddable
class CreditPackageDTO(name: String,
                       ref: String,
                       priceCents: Int,
                       maxInstallments: Int = 1,
                       gateway: PaymentGateway,
                       @field:Min(1) var creditAmount: Int) : ChargeableDTO(name, ref, priceCents, maxInstallments, gateway) {

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
abstract class ChargeableEntity(@field:Valid @field:Embedded @field:JsonIgnore open var dto: ChargeableDTO) : IChargeableDTO by dto

@Entity
@Table(name = "credit_packages", uniqueConstraints = [UniqueConstraint(columnNames = ["gateway", "ref"])])
class CreditPackage(dto: CreditPackageDTO) :  ChargeableEntity(dto) {

in short terms

I've a dto and a childDto that extends from it...
i've a base entity class which takes dto as constructor parameter and a child entity class that takes the childDto as parameter

when i load the child entity class from database using JPAREPOSITORY... the $$delegateDto IS ALWAYS NULL and then causes null pointer exception

what am i doing wrong?

1

There are 1 best solutions below

0
On

Just came across this question and had a similar issue that may be worth sharing:

In my case, the backing foo$delegate field for a lazy initialized property was null after the entity was created. Also, @Transient fields were not initialized correctly.

It turned out that it was caused by missing default constructors within the entity inheritance chain (I used the kotlin-noarg plugin so JPA was working fine in general).

Potential Solution:

Add default values for the dto parameters in ChargeableEntity and CreditPackage (and possibly also for the DTO constructors).

Not sure if this the complete solution, but it seems to be a necessary condition.