javaweb-servicesrestjpabidirectional-relation

Including all @OneToMany Entities in Restful-WebService response?


First Post here,so please excuse any noobish approaches to best get your attention / help me you find an answer. :)

Without going into too much detail of my actual Program:

I have a User who can register many Devices which can be associated to many Remotes which can have many Buttons ( Commands (LIRC Commands to be precise)).

Here is my Code for the 4 Entities' @ManyToOne and @OneToMany Sections.

USERS

@OneToMany(mappedBy = "user")
private List<Devices> devices;

DEVICES

@ManyToOne
@JoinColumn(name = "USER_ID")
private Users user;

@OneToMany(mappedBy = "device")
private List<Remotes> remotes;

REMOTES

@ManyToOne
@JoinColumn(name = "DEVICE_ID")
private Devices device;

@OneToMany(mappedBy = "remote")
private List<Commands> commands;

COMMANDS

@ManyToOne
@JoinColumn(name = "REMOTE_ID")
private Remotes remote;

They all work fine and the Database entries all have the appropriate foreign keys, and if I've understood correctly this should be bi-directional.

To My Question:

Is there a way my Restful Webservice Request can respond to a findAll() on the User by not only responding with the User but also with all the data from Devices in turn returning all the Devices' Remote's and the Commands which belong to the Remote.

@GET
@Override
@Produces({"application/json"})
public List<Users> findAll() {
    return super.findAll();
}

If need be I'll have to go through all the entities and patch together a JSON myself, but before I embark on that journey I was wondering if there's an easier way of going about my problem.

Cheers


Solution

  • Quick Fix:

    I had to change the Fetch and cascade settings for all of my @OneToMany's and @ManyToOnes' in my Entities.

    @XmlTransient
    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "USER_ID")
    private Users user;
    
    @OneToMany(
            mappedBy = "device",
            fetch = FetchType.EAGER,
            cascade = {CascadeType.REMOVE, CascadeType.MERGE,CascadeType.PERSIST})
    private List<Remotes> remotes;