I'm developing a relatively large project using Spring Boot, and in a general way I'm pretty happy with it, but I'm having some problems that in my mind should't be a problem.
First of all, One-To-One Relationship. It's frustrating that it doesn't work as it should (at least in my mind).
I have two entities, User
and UserProfile
, for example. They have One-To-One relationship, but most of the time I only need the User
data, but it fetches (no matter what I try, and oh boy, I tried the world suggestions on every post for 5 pages of Google).
So there is my first question, is there a way to be able to lazy fetch One-To-One relationship in JPA and Spring? (Because most of the posts are more than 2-3 years old).
The other problem I have is about to build a JSON response in a "dynamic" way. I did some stuff using Rails and was very happy with JBuilder
or even the to_json
that gave me the ability to build the json response depending on the controller and my needs at the moment.
In Spring I saw the following solutions:
Jackson @JsonView
(which doesn't solve entirely my problem because the responses are not that static and a attribute can't be assigned to multiple views (as far as I understood the concept));HashMap
like I build .json.jbuilder
on Rails (but this kills my performance as sometimes it has relationships so a lot of for
to build the json, and also this looks like a ugly walkthrough).I'm looking for some directions from someone that someday may have encountered one of this problems because it's killing me not being able so solve problems that in my mind should not be this hard.
EDIT 1
Already tried to add optional = false
on the @OneToOne
annotation to solve the Eager load of OneToOne relationship as @snovelli suggested. Example:
@OneToOne(optional=false, fetch = FetchType.LAZY)
public UserProfile getUserProfile(){ ... }
Regarding 'dynamic' JSON: Use DTOs.
This has the advantage of tailoring the objects to be serialized to the exact needs of the client consuming the resulting JSON. Also, the domain model (Hibernate entities) is decoupled from the JSON (de)serialization logic, allowing the two to evolve independently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With