Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSTing to a collection association using Spring Data Rest

I am have difficulty creating a collection association to which I can POST. I have two entities, Device and Group, having a Many to Many relationship. such that a Device may be in zero or more groups and a Group may contain zero or more Devices.

I can create new Device and Group entities by POSTing to /api/devices and /api/groups/. From my reading of the docs a Device in devices collection should have a RestResource that represents the collection of groups that the device is a member of (ie. /api/devices/{deviceId}/groups. This is an "association resource" and as it is an instance of Set<Group> I would have thought that it was regarded as a collection association. I can get and PUT uri-lists to this association, but when I post to it I get a 404.

The list could become quite large and I would like to be able to post a new link to the collection association, without having to download the whole thing modify it and PUT it back.

The documenation says that this should be supported, but I am having no luck.

Any suggestions would be most 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 one has a repository declared:

public interface DeviceRepository extends PagingAndSortingRepository<Device, Long> {
}

public interface GroupRepository extends PagingAndSortingRepository<Group, Long> {        
}
like image 829
OwainD Avatar asked Feb 11 '23 07:02

OwainD


1 Answers

Make use of PATCH, that way you don't have fetch existing collection. Just call PATCH with new link and existing collection gets updated. For example:

Add a new link (device) to a 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
like image 85
charybr Avatar answered Feb 13 '23 03:02

charybr