I was in a situation where I need to refer parent key id in child table. This is one-to-one relationship.
The child table only get the record when certain situation occurred. So not all records from parent are in child table but whatever the records contain by child are in parent table.
I made the changes in the code, when the child records gets inserted into the table, making sure it has a parent id with it.
I want to refer the records from child table and when I fetch them I also need the parent record associated with it.
I am using JPA and I handled the situation by making the following changes into the POJO classes.
The Parent class:
The Child class:
The code is working fine and I don't have any issue with it but just want to understand the things I am doing are right to define and drive the relation between parent and child.
Or is there any other way/workaround to handle the situation in much better way.
The question I asked because I am new to JPA and want to understand its basics.
Parent/child isn't One-to-One. It's one-to-Many on the parent and Many-to-One on the child entity. Whether you define the mappings unidirectionally or bi-directionally is up to you.
A fully bi-directional mapping would include a collection of Child Entity. You can make this lazy-fetch or eager-fetch, depending on how you expect to use it. The child Entity would have a ManyToOne relationship back to its parent.
Normally you do the linkages using the Entity property name as the reference key. That may or may not be the same name as the database column name, depending on how the Entity maps to the underlying database schema. In my case column names are often things like "CREATE_DATE", and the corresponding Entity property name is java-style (createDate).
An IDE is no substitute for an Intelligent Developer.