Skip to content
Advertisement

JPA @OnetoOne self reference relationship with both columns non null

I have an existing database table For e.g. T_STUDENTS on top of which I have to create a JPA entity. All three columns in the table are NON NULL and the table has a self-reference as mentor_id

JavaScript

Each student has a mentor who is also a student. There is a strict OneToOne relationship between the student and the mentor. For id 1, there can’t be any mentor, therefore it has the mentor id as it’s own id. The ids are generated using a database sequence.

The problem is that while generating the first record with id 1, hibernate is not assigning the same id as mentor id even though I have created necessary relationships. Since columns can’t be null and hibernate is not assigning mentor_id, SQLConstraint nonnull exception is thrown.

Following is how I have created the relationship.

JavaScript

I have set CascadeType.NONE because else hibernate tries to retrieve 2 id’s from sequence and tries to create 2 records which are not desirable.

The problem is how can I insert the very first record. Following is how the insert is being done.

JavaScript

If I change the relationship annotation to @ManyToOne since technically mentor_id is 1 is mapped to 2 students, I get the following exception

JavaScript

Edit 1: If relationship type changed to @ManyToOne and cascade is removed following error is observed.

JavaScript

Edit 2: Changed the cascade type to cascade = CascadeType.PERSIST and hibernate tries to persist the mentor as a separate record. I verified from logs that it tries to retrieve 2 different sequence ids and creates 2 insert queries, with both mentor_id as null.

Advertisement

Answer

NOTE: Finally I found the root cause. I was using Lombok builder in the JPA entity and it does not support the self-reference relationship yet.

I switched to public setters and it worked fine. See the link below for more details https://github.com/rzwitserloot/lombok/issues/2440#event-3270871969

You can ignore the below solution.

I’m not very proud of the solution, but here is how I achieved it.

1.Removed auto sequence generation from the id.

JavaScript

to

JavaScript

2.Changed the mapping to the simple foreign key field.

JavaScript

to

JavaScript

3.Created a method to retrieve the sequence manually and then assigned the value to both ‘id’ and ‘mentorId’

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement