问题
I have an @Entity called User. It has a Set of Changesets as follows:
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="user")
private Set<Changeset> changesets = new HashSet<Changeset>();
I have a UserRepository:
@Repository
@RestResource(path = "users", rel = "users")
public interface UserRepository extends JpaRepository<User, Long>{ }
And a ChangesetRepository:
@Repository
@RestResource(path = "changesets", rel = "changesets")
public interface ChangesetRepository extends JpaRepository<Changeset, Long> { }
Calling GET on http://localhost:8080/changesets/
or http://localhost:8080/users/
yields a paged response.
If I call GET on http://localhost:8080/users/1/changesets
then I get all the results in a single array and no paging occurs.
Is there a way to indicate to Spring Data Rest that I want to return the changesets collection in a pageable manner when accessing it through its parent User? The Set of changesets will grow quickly and I'd rather not return tons of results in a single page.
EDIT:
As suggested by Willie Wheeler I added this to my ChangesetRepository to make it searchable:
@RestResource(path = "byUser", rel = "byUser")
public Page<Changeset> findByUser(@Param("id") User user, Pageable p);
I left the relationship bidirectional, but was also able to hide the link to changesets from a user by using @RestResource(exported=false)
on the Set of changesets.
Side Note: It appears that setting the relationship to exported=false hides the link, but doesn't actually remove the mapping. /users/1/changesets isn't advertised, but it's still valid.
回答1:
I don't think that SDR directly supports the approach you describe.
There's another approach you might take though. Instead of using a bidirectional relationship between Person
and Changeset
, make it unidirectional from the Changeset
to the Person
. Then in your ChangesetRepository
include a method like this:
@RestResource(path = "find-by-person")
Page<Changeset> findByPerson(@Param("person") Person person, Pageable pageable);
(I'm just doing that from memory, so you might require minor adjustments.)
From a design perspective I think this is stronger anyway, since I imagine that a person's changesets are relevant in a limited number of contexts. It might be more appropriate to query for changesets rather than bundling them with the person.
来源:https://stackoverflow.com/questions/21469538/spring-data-rest-pageable-child-collection