For Spring Boot
working with Spring Data
for a uni-directional @OneToMany
relation,
such as Parent
and Child
, their codes are respectively as follows:
@Entity
@Table(name="parent")
public class Parent implements Serializable {
...
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.REMOVE, orphanRemoval=true)
@JoinColumn(name="parent_id")
@OrderBy("id")
private final Set<Child> children = new LinkedHashSet<>();
...
}
and
@Entity
@Table(name="child")
public class Child implements Serializable {
...
}
And having a custom ParentRepository
interface extending CrudRepository<T,ID>
, it has defined explicitly a custom method named findByIdWithChildren
working with @Query
and using JOIN FETCH
Therefore using Spring MVC - through HTML (Thymeleaf
) - through @GetMapping
is possible:
Group I
- (A) Find and show only a specific
Parent
- through the defaultfindById
method. (Ok) - (B) Find and show a specific
Parent
with all itsChild
- through the customfindByIdWithChildren
method. (Ok) - (C) Find and show only all the
Parent
- through the defaultfindAll
method. (Ok)
Therefore until here all is Ok. The problem is when REST
is used, exists now the following behavior as follows.
Group II
- (A) behaves as (B) Group I (Not desired)
- (B) behaves as (B) Group I (Ok)
- (C) Find and show all the
Parent
but with all theirChild
(Not desired)
Using @JsonBackReference
as follows
@JsonBackReference
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.REMOVE, orphanRemoval=true)
@JoinColumn(name="parent_id")
@OrderBy("id")
private final Set<Child> children = new LinkedHashSet<>();
happens as follows:
Group III
- (A) Find and show only a specific
Parent
- through the defaultfindById
method. (OK) - (B) Find and show a specific
Parent
but without all itsChild
- through the customfindByIdWithChildren
method. (Not desired) - (C) Find and show only all the
Parent
- through the defaultfindAll
method. (OK)
Question
- How to reach the same kind of output for Rest as HTML?
Show only a specific parent (without its children), show a specific parent with its children, show only all the parents (without their children)