This project was setup to be a playground to experiment with:
- spring-data-jpa
- Hibernate
- There are 3 tables
user,user_departmentanduser_address(Not the ideal way to organize data) - Use the
database.sqlto create the tables and insert the related data - There is a one to one mapping between
useranduser_department. Theuser_idcolumn onuser_departmentreferences theidcolumn on theusertable. - There is a one to one mapping between
useranduser_address. Theuser_idcolumn onuser_addressreferences theidcolumn on theusertable.
- How to set establish
@OneToOnerelationship 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
Userclass (representsusertable ) that has a 1-1 mapping withUserDepartmentclass (representuser_department) When querying forUseralone,UserDepartmententities should not be fetched unless specified. To achieve thisfetch = FetchType.LAZYandoptional=falseneed to be specified in the@OneToOneannotation that is not on the owning side of the relationship By default spring-boot'sObjectMapperdoes not support lazy loading and looks for the relatedUserDepartmentobject 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 anObjectMapperthat 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
Hibernate5Moduleas:@Bean public Module datatypeHibernateModule() { return new Hibernate5Module(); }
Although the
Hibernate5Moduledoes not look for the related entities it returns them asnull.To get around this
Userclass need to be annotated with@JsonInclude(JsonInclude.Include.NON_EMPTY)