C
C
Chvalov2018-10-01 04:53:47
Hibernate
Chvalov, 2018-10-01 04:53:47

How to output nested OneToMany data?

There is an Entity class:

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private String method;

    private String url;
    @OneToMany
    private List<QueryParams> queryParams;

The problem is that Json is sent to the page without QueryParams data, it seems to be there, but empty E4qouxv.png
Controller:
@GetMapping("/find/{name}")
    public List<Test> find(@PathVariable String name) {
        return testService.findByName(name);
    }

    @GetMapping("get/{id}")
    public Optional<Test> gets(@PathVariable("id") Long id) {
        return testService.findById(id);
    }

At the same time, if you execute Evaluate Expression in the debug, you can see that the data is coming: 5D44GVc.png
What did I miss?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Conacry, 2018-10-01
@Chvalov

Hello.
For a complete understanding, there is not enough code for your service class and dao class (if any). In my opinion, the problem is in the strategy of loading related objects (@OneToMany).
In Hibernate/JPA, there are two types of strategy for loading related objects: immediately (FetchType=EAGER) or do it only when they are accessed (FetchType=LAZY). In fact, in the case when the subject area has any complicated structure of relations between objects, the choice has already been made - to load half the database for the sake of one object, as it would be with FetchType=EAGER, to put it mildly, unreasonable. Therefore, lazy initialization in the case of collections is the most preferred strategy for initializing related objects [ https://habr.com/post/111911/].The default for a OneToMany relationship is FetchType=LAZY.
So the problem is with loading related objects from the database.
In the code of your model, you need to add an annotation with a choice of the type of loading strategy:

...
@OneToMany(fetch = FetchType.LAZY)
private List<QueryParams> queryParams;
...

And in a service class or DAO class before
...
return testObject;
...
put a line
In this case, Hibernate will load all related objects.
If you have any questions, write, ready to answer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question