Spring Rest Data projection @OneToOne property not loading

560 Views Asked by At

I have these three classes:

@Entity
public class Trip {

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private List<Leg> legs;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private List<TripDetail> details;

  /* snip */
}

@Entity
public class TripDetail {

  @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private CustomComponents customComponents;

  /* snip */
}


@Entity
public class CustomComponents {

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private List<CustomComponent> existingComponents;

  /* snip */
}

And this projection:

@Projection(name = "withUsages", types = { Trip.class })
public interface TripWithUsagesProjection {
  List<LegWithUsagesProjection> getLegs();

  List<TripDetail> getDetails();
} 

Now, when I do a GET on my trips API with the projection then the customComponents object in TripDetail in the returned JSOn is null.

If I change the customComponents property in TripDetail to load eagerly (fetch=FetchType.EAGER) then the resulting JSON is correct (as in it includes customComponents' data inline).

I like to understand why that is?

TripDetail has a bunch of other properties not shown for brevity (some @OneToMany, some BigDecimal, Strings and other properties). This is the only @OneToOne. Why is a @OneToOne behaving differently here?

1

There are 1 best solutions below

0
On

Looking at this piece of code

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private CustomComponents customComponents;

You are telling Hibernate to load CustomComponents in LAZY way. i.e It will load its detail only when needed.

So if you are debugging and look for customComponents it will be null.

But further on when you try to read some data from CustomComponents, it should load customComponents details.

As Hibernate will fire another query under the hood saying

select * from CustomComponents where id = ?

Thats's how LAZY works

More details here