Search code examples
kotlinneo4jneo4j-ogm

Non null relationships in primary constructor of entity


I'm creating application with Spring Data Neo4j and Kotlin. I use standard kotlin way to declare entities (class with primary constructor). Everything worked fine until I wanted to create simple, one-to-many and mandatory relationship between my entities. When I'm calling .findAll() on my repository I get Parameter specified as non-null is null: method ...model.Campaign.<init>, parameter client.

I tried to call .findAll(depth = 1) to load related entities to my entity but that didn't help.

@NodeEntity
class User(var name: String)
{
    @Id @GeneratedValue
    var id: Long? = null
}

@NodeEntity
class Campaign(
    var name: String,
    @Relationship(type = "CLIENT", direction = Relationship.OUTGOING)
    var client: User)
{
    @Id @GeneratedValue
    var id: Long? = null
}

interface CampaignRepository : Neo4jRepository<Campaign, Long>

//...

campaignRepository.save(Campaign("C1", user))

campaignRespository.findAll()

Of course, I can just declare var client: User? as nullable and everything is fine. But, since in my model I will have both mandatory and optional relationships I want to know if there's a way to overcome this.


Solution

  • I found a solution, but not very elegant:

    @NodeEntity
    class Campaign(
        var name: String,
        client: User?)
    {
        @Id @GeneratedValue
        var id: Long? = null
    
        @Relationship(type = "CLIENT", direction = Relationship.OUTGOING)
        lateinit var client: User
    
        init
        {
            client?.let { this.client = it }
        }
    }