Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

hibernate - Spring Data Rest Pageable Child Collection

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...