robert trudel
robert trudel

Reputation: 5749

jpa lazy return all element

I have two class Brand and Model. I use lazy loading.

@Entity
public class Brand {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long brandId;

  private String brand;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "brand")
  @JsonManagedReference
  private List<Model> modelList;
  ...
}

@Entity
public class Model {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long modelId;

  private String model;

  @ManyToOne
  @JoinColumn(name = "brandId")
  @JsonBackReference
  private Brand brand;
  ...
}

In my repository i use standard method findAll.

public interface BrandRepository extends JpaRepository<Brand, Long>

When i do a call to get Brand

curl http://localhost:8080/brands

I get also model

[
{
"brandId":1, "brand":"Toyota", "modelList":[
{
"modelId":1, "model":"Echo" }, {
"modelId":2, "model":"Corolla" } ] }, {
"brandId":2, "brand":"Honda", "modelList":[
{
"modelId":3, "model":"Civic" }, {
"modelId":4, "model":"Accord" } ] }, {
"brandId":3, "brand":"Kia", "modelList":[
{
"modelId":5, "model":"Sorento" } ] }, {
"brandId":4, "brand":"Ford", "modelList":[
{
"modelId":6, "model":"Mustang" } ] } ]

Are there something missing?

Upvotes: 0

Views: 86

Answers (1)

Nitin Arora
Nitin Arora

Reputation: 2668

If you want to omit models from Brand, you should put @JsonBackReference on modelList instead of @JsonManagedReference.

@JsonManagedReference is the forward part of reference – the one that gets serialized normally.

@JsonBackReference is the back part of reference – it will be omitted from serialization.

Hope this helps.

Upvotes: 1

Related Questions