How to add elements in a many-to-many relationship via Spring's @RepositoryRestResource REST API?
Asked Answered
V

2

12

I'm having trouble figuring out exactly how to use the @RepositoryRestResource interface to create many-to-many relationships between two fairly simple entities.

For example, I have a simple parent-child entity relationship like this:

@Entity
public class ParentEntity {
    @Id
    @GeneratedValue
    private Long id;

   @ManyToMany
   private List<ChildEntity> children;
}

@Entity
public class ChildEntity {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToMany(mappedBy="children")
    private List<ParentEntity> parents;
}

My repositories are using the vanilla Spring @RepositoryRestResource HATEOS API:

@RepositoryRestResource(collectionResourceRel = "parents", path = "parents")
public interface ParentRepository extends PagingAndSortingRepository<ParentEntity, Long> {
}

@RepositoryRestResource(collectionResourceRel = "children", path = "children")
public interface ChildRepository extends PagingAndSortingRepository<ChildEntity, Long> {
}

I’ve been successful in using POST to create the individual ParentEntity and ChildEntity but I can’t seem to figure out how to PUT/PATCH the relationships between the two using the built-in interface.

It seems like I should be able to use a PUT to send JSON to something like http://localhost:8080/api/parents/1/children, but so far I'm not finding a structure that works.

Verleneverlie answered 8/10, 2014 at 14:30 Comment(0)
V
14

I found an answer here: How to update reference object in Spring-data rest?

By using "Content-Type: text/uri-list" instead of JSON, it is possible to "add" a resource to the collection with a PUT and pass in the URI. You can remove the resource with a DELETE.

After some digging, I discovered that the Spring documentation does describe this: http://docs.spring.io/spring-data/rest/docs/2.2.0.RELEASE/reference/html/#repository-resources.association-resource.

Verleneverlie answered 9/10, 2014 at 13:19 Comment(1)
Thanks for giving the link to an answer and the docs. That part of the docs makes more sense after seeing a concrete example.Ominous
V
4

I always hated that text/uri-list content-type, so I did some research and it turned out there is also an undocumented JSON format which can be used:

{
  "_links":{
    "rel":"/555",
    "rel":"/556"
  }
}

The rel of the links could be anything except empty string, they could be all the same. The link part could be the whole URL form the self link of the referenced object, but the last part of the URL is enough. ( forseslash +id)

Votary answered 23/1, 2019 at 14:35 Comment(1)
this also works for 2.2.0 M4. ``` { "_links":{ "1":{"href": "/555"}, "1":{"href": "/556"} } } ```Bedside

© 2022 - 2024 — McMap. All rights reserved.