Making database @Entity fields less mutable

I’m using Kotlin with the JPA plugin to make database entity classes to use with Hibernate (or eBean in another project). Each user is associated with exactly one company and companies can have many users:

@Entity
class User(
        @get:ManyToOne(fetch = FetchType.LAZY)
        @get:JoinColumn(name = "company_id", nullable = false)
        var company: Company,
...

Thinking that Kotlin is good with immutability and the company should really never change, I tried changing var to val. I hoped the JPA plugin would magically make a set method that works for Hibernate, but doesn’t show up at compile time. Instead, IntelliJ warns, “For property-based access, both setter and getter should be present.” If I ignore that and try to compile, I get a huge compile error that starts with:

Error:Kotlin: [Internal Error] java.lang.AssertionError: There is no type parameter with violated upper bound for ‘upper bound violated’ error…

It was worth a try.

My second choice, was to deprecate the setter. I’ve done this before in Java. Hibernate doesn’t care about deprecation, but I get errors while I’m coding which are enough to keep me from doing bad things. So I added:

@set:Deprecated("Do not modify")

This kind of works, but it seems to deprecate both the get and the set for my Java code that uses this class.

Thoughts? Ideas?

1 Like