This project was setup to be a playground to experiment with:
- spring-data-jpa
- Hibernate
- There are 3 tables
user
,user_department
anduser_address
(Not the ideal way to organize data) - Use the
database.sql
to create the tables and insert the related data - There is a one to one mapping between
user
anduser_department
. Theuser_id
column onuser_department
references theid
column on theuser
table. - There is a one to one mapping between
user
anduser_address
. Theuser_id
column onuser_address
references theid
column on theuser
table.
- How to set establish
@OneToOne
relationship mapping between objects with lazy loading - How to use multiple
NamedEntityGraphs
-
Owning side of a relationship in hibernate This stackoverflow question: https://stackoverflow.com/questions/2749689/what-is-the-owning-side-in-an-orm-mapping helps understand these concepts This link in the comment: https://www.javacodegeeks.com/2013/04/jpa-determining-the-owning-side-of-a-relationship.html gives a very good explanation
-
Lazy loading In the example (not an ideal example) in this project. We have a
User
class (representsuser
table ) that has a 1-1 mapping withUserDepartment
class (representuser_department
) When querying forUser
alone,UserDepartment
entities should not be fetched unless specified. To achieve thisfetch = FetchType.LAZY
andoptional=false
need to be specified in the@OneToOne
annotation that is not on the owning side of the relationship By default spring-boot'sObjectMapper
does not support lazy loading and looks for the relatedUserDepartment
object and results in an exception being thrown The exception goes like:could not initialize proxy - no Session (through reference chain:
To circumvent this we need to use anObjectMapper
that supports lazy loading That is where we need to use: https://github.com/FasterXML/jackson-datatype-hibernate This helps circumventing this issue.Include the dependency as:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-hibernate5</artifactId> <version>2.9.0</version> </dependency>
Inject the
Hibernate5Module
as:@Bean public Module datatypeHibernateModule() { return new Hibernate5Module(); }
Although the
Hibernate5Module
does not look for the related entities it returns them asnull
.To get around this
User
class need to be annotated with@JsonInclude(JsonInclude.Include.NON_EMPTY)