POSTing to a collection association using Spring Data Rest
I find it difficult to create a collection to which I can POST. I have two objects, Device and Group, that have a many-to-many relationship. so a device can be in zero or more groups, and a group can contain zero or more Devices.
I can create new Device and Group objects by POSTing to / api / devices and / api / groups /. From my reading of the docs in the device, there should be a RestResource in the device collection that represents the collection of groups the device is a member of (ie. / Api / devices / {deviceId} / groups. This is an "association resource" and since this is an instance Set<Group>
I would think that it is treated as a collection association. I can get and PUT uri-list
to this association, but when I post I get a 404.
The list can get quite large and I would like to be able to post a new collection association link without downloading the whole thing or changing it.
the documenation says this should be supported, but I had no luck.
Any suggestions will be highly appreciated.
These domain classes are defined as:
@Entity
public class Device {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToMany(targetEntity = Group.class, cascade = CascadeType.ALL)
private Set<Group> groups;
// getters, setters
}
and,
@Entity(name="device_groups")
public class Group {
@Id @GeneratedValue
private Long id;
private String name;
@ManyToMany(mappedBy = "groups")
private Set<Device> devices;
// getters, setters
}
Each has a repository declared:
public interface DeviceRepository extends PagingAndSortingRepository<Device, Long> {
}
public interface GroupRepository extends PagingAndSortingRepository<Group, Long> {
}
source to share
Use PATCH this way you don't have a selection of an existing collection. Just call PATCH with the new link and the existing collection will be updated. For example:
Add new link (device) to collection:
curl -i -X PATCH -H "Content-Type: text/uri-list" -d "http://localhost:8080/app/device/1" http://localhost:8080/app/group/87/devices
Add multiple devices to an existing collection:
curl -i -X PATCH -H "Content-Type: text/uri-list" -d "
http://localhost:8080/app/device/2
http://localhost:8080/app/device/3" http://localhost:8080/app/group/87/devices
source to share