Using FetchType.LAZY with JBoss/Wildfly and JSON

35 Views Asked by At

In WildFly, I defined an entity like this:

@Entity
@Table("OrderTable")
@JsonIgnoreProperties(ignoreUnknown = true)
public class OrderEntity {
    private List<ItemEntity> items;

    @OneToMany(targetEntity = ItemEntity.class, cascade=CascadeType.ALL)
    @JoinColumn(name="ITEM_ID")
    public List<ItemEntity> getItems() {...}
    public void setItems(List<ItemEntity> items) {...}
} 

Then using JaxRS, I defined this to retrieve the data

    @GET
    @Path("/{id}")
   public Response getOrder(@PathParam("id") String id) {
        OrderEntity order= orderService.retrieveOrder(id);
        return Response.ok(order).build()
   }

My issue is while the orderService business layer have no problem returning the order entity, when I attempt to return the Response.ok(), mapping to JSON, it would complain my items are not loaded: "failed to lazily initialize a collection of role"

Does this mean I MUST load all the relations in order to make this work, even if I do not need to access the items relations?

1

There are 1 best solutions below

1
Anton Kozub On

JSON doesn't know what do you need if you didn't say that explicitly.

The ways to solve that:

  1. Add @JsonIgnore to getItems if you don't need them.
  2. Add cascade=EAGER to load items if you do need them.
  3. Add @Transaction to getOrder method to load items (this way is not recommended, but technically it helps).
  4. Add some intermediate DTO layer - in this case you can have several DTOs for one entity for different cases, they will have a different set of fields depending on what you need.
  5. The way that also allows to load different data sets but without DTO - JPA Entity Graph.