I have two database classes, Plan and Strategy with Hibernate/JPA annotations:
@Entity
@Table(name = "plan")
class Plan() : Idd {
@get:Id
@get:GeneratedValue(strategy = IDENTITY)
@get:Column(name = "id", unique = true, nullable = false)
override var id: Long = 0
@get:ManyToOne(fetch = FetchType.LAZY)
@get:JoinColumn(name = "top_strat_id", nullable = false)
var topStrat: Strategy?
}
@Entity
@Table(name = "strategy")
class Strategy(
@get:ManyToOne(fetch = FetchType.LAZY)
@get:JoinColumn(name = "plan_id", nullable = false)
var plan: Plan
) : Idd {
@get:Id
@get:GeneratedValue(strategy = IDENTITY)
@get:Column(name = "id", unique = true, nullable = false)
override var id: Long = 0
}
You can see that there is a circular reference where every Strategy has a Plan and every Plan has a topStrat. I'm pretty sure that I need to persist the Plan to the database so that it gets an autogenerated ID. Then I create a new Strategy with my plan and save it so that it gets an autogenerated ID too. I need to leave Plan.topStrat nullable for creation.
Once they are created, plan.topStrat should never be null again (that's a business rule). So it's kind of weird to be calling myPlan.topStrat!! in half a dozen places. Is there some simple standard way of dealing with this? Some idiom I don't know about?
This happens in a few places in a database I work on. Another example is our User table which gained too many columns over time. We split it into User and User2. User has the stuff that's needed on every screen. User2 has the things that are accessed occasionally. I need to leave User.user2 null to create the user and get the ID. Then I think I actually set User2's ID to equal the User id it relates to ('cause it's 1:1). Once it's saved, User.user2 can never be null again.
It's a corner case, and not a big deal. But if there's some simple and elegant way of dealing with this, I'd love to know.
You should be able to use lateinit
. Though you'll need to annotate @field:
instead of @get:
, or the JPA provider will throw when trying to access it.