Elasticsearch Spring repository search using multiple fields - java

I have a Spring Boot application connected to an Elasticsearch instance containing this sample data. I am currently able to search for a specific field, but the moment I add the second one in the request, I don't have any results (each of the fields are fine on their own). How can I get the correct results?
Here are my classes:
#Document(indexName = "bank", type = "account", replicas = 0)
public class Account {
#Id
private String id;
private long accountNumber;
private long balance;
private String firstname;
private String lastname;
private long age;
private String gender;
private String address;
private String employer;
private String email;
private String city;
private String state;
}
public interface AccountRepository extends ElasticsearchRepository<Account, String> {
Page<Account> findByGenderAndStateAllIgnoreCase(String gender, String state, Pageable pageable);
}
#Service
public class AccountServiceImpl implements AccountService {
#Autowired
private AccountRepository repository;
#Override
public Account save(Account account) {
return repository.save(account);
}
#Override
public Account findOne(String id) {
return repository.findOne(id);
}
#Override
public Collection<Account> findAll(PageRequest request) {
return repository.findAll(request).getContent();
}
#Override
public Collection<Account> findByGenderAndState(String gender, String state, PageRequest request) {
return repository.findByGenderAndStateAllIgnoreCase(gender, state, request).getContent();
}
}
#Controller
#RequestMapping("/bank")
public class BankController {
#Autowired
private AccountService accountService;
#GetMapping("/accounts")
public
#ResponseBody
Collection<Account> accounts(#RequestParam(name = "gender", required = false, defaultValue = "*") String gender,
#RequestParam(name = "state", required = false, defaultValue = "*") String state,
#RequestParam(name = "page", required = false, defaultValue = "0") int page,
#RequestParam(name = "size", required = false, defaultValue = "10") int size) {
return accountService.findByGenderAndState(gender, state, new PageRequest(page, size));
}
}
Here is the query that is sent to Elasticsearch from Spring Boot:
[
{
"from": 20,
"size": 20,
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "f",
"fields": [
"gender"
],
"default_operator": "and"
}
},
{
"query_string": {
"query": "dc",
"fields": [
"state"
],
"default_operator": "and"
}
}
]
}
}
}
]

Turns out I was querying for the page #1, instead of #0. The results are showing correctly now.

Related

why don't you see the "keys" in the json?

when I enter postman, I get the json, but without his "keys" why? Maybe I'm making a mistake and I haven't noticed. Some help please.
I am using a stored procedure to be able to do a crud.
this is the json that shows me postman. Shows me without his "key"
{
"data": [
[
1,
"aaa",
"aaa#gmail.com"
],
[
2,
"bbb",
"bbb#gmail.com"
],
[
3,
"ccc",
"ccc#gmail.com"
]
]
}
I would like to get something like this.
{
"data": [
{
userCod: 1,
userName: "aaa",
userEmail: "aaa#gmail.com"
},
{
userCod: 2,
userName: "bbb",
userEmail: "bbb#gmail.com"
},
{
userCod: 3,
userName: "ccc",
userEmail: "ccc#gmail.com"
}
]
}
I leave the code
public class ApiResponse {
private List<UserTest> data;
public List<UserTest> getData() {
return data;
}
public void setData(List<UserTest> data) {
this.data = data;
}
}
#Entity
#Table(name = "tbUsers")
public class UserTest implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userCod")
private Long id;
#Column(name = "userName")
private String name;
#Column(name = "userEmail")
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
#Repository
public class ClienteDaoImpl implements IClienteDao{
#Autowired
private EntityManager em;
#SuppressWarnings("unchecked")
#Override
public ApiResponse mntUsers(int op) {
ApiResponse api = new ApiResponse();
Session session = em.unwrap(Session.class);
ProcedureCall call = session.createStoredProcedureCall("sp_MntUser");
call.registerParameter(1, Integer.class, ParameterMode.IN);
call.setParameter(1, op);
call.execute();
api.setData(call.getResultList());
return api;
}
}
#RestController
#RequestMapping(value = "/mntUsers")
public class ClienteController {
#Autowired
private ClienteServiceImpl serviceImpl;
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> CrudUsers(#RequestParam(value = "option", required = true) Integer op) {
return new ResponseEntity<>(serviceImpl.mntUsers(op),HttpStatus.OK);
}
}
Create a method called getCollectionType
public static <T, C extends Collection<T>> C getCollectionType(Iterable<?> from, C to, Class<T> listClass) {
for (Object item: from) {
to.add(listClass.cast(item));
}
return to;
}
Then use it on the following line:
api.setData(getCollectionType(call.getResultList(),
new ArrayList<UserTest>(),
UserTest.class));

Spring boot HATEOAS not automatically adding links to related resources

Links are not automatically being provided for resources when using HATEOAS to fetch resource collections.
When fetching a collection of ThreadResource with '/forum/threads', the response is:
{
"_embedded": {
"threadList": [
{
"posts": [
{
"postText": "This text represents a major breakthrough in textual technology.",
"thread": null,
"comments": [],
"thisId": 1
},
{
"postText": "This text represents a major breakthrough in textual technology.",
"thread": null,
"comments": [],
"thisId": 2
}
],
"createdBy": "admin",
"updatedBy": null,
"thisId": 1
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/forum/threads?page=0&size=10"
}
},
"page": {
"size": 10,
"totalElements": 1,
"totalPages": 1,
"number": 0
}
}
I was expecting a JSON array of posts (instead of links to associated posts collection), like below:
{
"_embedded": {
"threadList": [
{
"createdBy": "admin",
"updatedBy": null,
"thisId": 1,
"_links": {
"posts": {
"href": "http://localhost:8080/forum/threads/1/posts"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/forum/threads?page=0&size=10"
}
},
"page": {
"size": 10,
"totalElements": 1,
"totalPages": 1,
"number": 0
}
}
I could manually build and add links in ResourceProcessor implementation classes and exclude the collection from being rendered using #JsonIgnore, but I have never had to do this before. What I am doing wrong?
The relevant classes are provided below. Thanks in advance!
#Entity
public class Thread {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany
private List<Post> posts;
#Column(name = "created_by")
private String createdBy;
#Column(name = "updated_by")
private String updatedBy;
public Thread() { }
#PrePersist
public void prePersist() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
posts = new ArrayList<>();
createdBy = auth.getName();
}
#PreUpdate
public void preUpdate() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
updatedBy = auth.getName();
}
public void submitPost(Post newPost) {
posts.add(newPost);
}
public Long getThisId() {
return id;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
#Entity
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String postText;
#ManyToOne(fetch = FetchType.LAZY)
private Thread thread;
#OneToMany
private List<Comment> comments;
public Post() { }
}
public class ThreadResource extends ResourceSupport {
private List<PostResource> postResources;
private String createdBy;
private String updatedBy;
public ThreadResource() {
}
}
public class PostResource extends ResourceSupport {
private String postText;
private ThreadResource threadResource;
private List<CommentResource> commentResources;
public PostResource() { }
#Component
public class PostResourceAssembler extends ResourceAssemblerSupport<Post, PostResource> {
public PostResourceAssembler() {
super(PostController.class, PostResource.class);
}
#Override
public PostResource toResource(Post entity) {
PostResource resource = super.createResourceWithId(entity.getThisId(), entity);
resource.setPostText(entity.getPostText());
return resource;
}
}
#Component
public class ThreadResourceAssembler extends ResourceAssemblerSupport<Thread, ThreadResource> {
private PostResourceAssembler postResourceAssembler;
public ThreadResourceAssembler(PostResourceAssembler postResourceAssembler) {
super(ThreadController.class, ThreadResource.class);
this.postResourceAssembler = postResourceAssembler;
}
#Override
public ThreadResource toResource(Thread entity) {
ThreadResource resource = super.createResourceWithId(entity.getThisId(), entity);
List<Post> posts = entity.getPosts();
List<PostResource> postResources = new ArrayList<>();
posts.forEach((post) -> postResources.add(postResourceAssembler.toResource(post)));
resource.setPostResources(postResources);
return resource;
}
}
#RestController
public class PostController {
private PostService postService;
#Autowired
public PostController(PostService postService) {
this.postService = postService;
}
#GetMapping("/forum/threads/{threadId}/posts/{postId}")
public ResponseEntity<Resource<Post>> getPost(#PathVariable long threadId, #PathVariable long postId) {
Post post = postService.fetchPost(postId)
.orElseThrow(() -> new EntityNotFoundException("not found thread " + postId));
Link selfLink = linkTo(PostController.class).slash(postId).withSelfRel();
post.add(selfLink);
return ResponseEntity.ok(new Resource<>(post));
}
#GetMapping
public ResponseEntity<PagedResources<Resource<Post>>> getPosts(PagedResourcesAssembler<Post> pagedResourcesAssembler) {
Pageable pageable = new PageRequest(0, 10);
Page<Post> posts = postService.fetchAllPosts(pageable);
PagedResources<Resource<Post>> resources = pagedResourcesAssembler.toResource(posts);
return ResponseEntity.ok(resources);
}
#PostMapping("/forum/threads/{threadId}/posts")
public HttpEntity<?> submitPost(#PathVariable long threadId) throws URISyntaxException {
Post post = postService.submitPost(threadId, new Post());
if (post != null) {
Link selfLink = linkTo(methodOn(PostController.class).submitPost(threadId)).slash(post.getThisId()).withSelfRel();
post.add(selfLink);
return ResponseEntity.created(new URI(selfLink.getHref())).build();
}
return ResponseEntity.status(500).build();
}
}
#RestController
public class ThreadController {
private ThreadService threadService;
private ThreadResourceAssembler threadResourceAssembler;
#Autowired
public ThreadController(ThreadService threadService,
ThreadResourceAssembler threadResourceAssembler) {
this.threadService = threadService;
this.threadResourceAssembler = threadResourceAssembler;
}
#GetMapping("/forum/threads/{threadId}")
public ResponseEntity<ThreadResource> getThread(#PathVariable long threadId) {
Thread thread = threadService.fetchThread(threadId)
.orElseThrow(() -> new EntityNotFoundException("not found thread " + threadId));
ThreadResource threadResource = threadResourceAssembler.toResource(thread);
return ResponseEntity.ok(threadResource);
}
#GetMapping("/forum/threads")
public ResponseEntity<PagedResources<Resource<ThreadResource>>> getThreads(PagedResourcesAssembler pagedResourcesAssembler) {
Pageable pageable = new PageRequest(0, 10);
Page<Thread> threads = threadService.fetchAllThreads(pageable);
PagedResources pagedResources = pagedResourcesAssembler.toResource(threads);
return ResponseEntity.ok(pagedResources);
}
#PostMapping("/forum/threads")
public HttpEntity<?> createThread() {
Thread thread = threadService.createThread();
return ResponseEntity.ok(thread);
}
#DeleteMapping("/forum/threads/{threadId}")
public HttpEntity<?> deleteThread(#PathVariable long threadId) {
Thread thread = threadService.fetchThread(threadId)
.orElseThrow(() -> new EntityNotFoundException("not found thread" + threadId));
threadService.closeThread(thread);
return ResponseEntity.ok().build();
}
}

Retrofit 2 return List from Json is empty

I have been fighting with Retrofit 2.3 for about 2 weeks now. The List always comes back as empty for me. It simply makes a call and gets the JSON information yet it won't process the list.
Json appears like this:
{
"users": [
{
"id": 2,
"name": "Users Name",
"username": "myusername",
"facebook_id": null,
"level": "1",
"birthdate": "1999-09-09T00:00:00+00:00",
"email": "user#gmail.com",
"activated": "",
"created": "2017-12-07T04:18:30+00:00",
"answers": [
{
"id": 31,
"question_id": 2,
"user_id": 2,
"answer": "School",
"questions": [
{
"id": 2,
"question": "Where did you meet your best friend?"
}
]
},
{
"id": 32,
"question_id": 3,
"user_id": 2,
"answer": "Dog",
"questions": [
{
"id": 3,
"question": "What was your first pet's name?"
}
]
}
]
}
],
"message": "Success"
}
Retrofit Interface class:
public interface RestInterface {
String url = "http://myurl.com";
/**
* Login
*
* #param username Username
* #param password Password
*
*/
#FormUrlEncoded
#Headers("User-Agent:My-Application")
#POST("login")
Call<userlogin> Login(#Field("username") String username,
#Field("password") String password);
}
Userlogin class:
public class userlogin {
#SerializedName("users")
#Expose
private List<users> users;
#SerializedName("message")
#Expose
private Object message;
public List<users> getUsers() {
return users;
}
public void setUsers(List<users> users) {
this.users = users;
}
public Object getMessage() {
return message;
}
public void setMessage(Object message) {
this.message = message;
}
}
users class:
public class users {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("username")
#Expose
private String username;
#SerializedName("facebook_id")
#Expose
private String facebookId;
#SerializedName("level")
#Expose
private String level;
#SerializedName("birthdate")
#Expose
private String birthdate;
#SerializedName("email")
#Expose
private String email;
#SerializedName("activated")
#Expose
private String activated;
#SerializedName("created")
#Expose
private String created;
#SerializedName("answers")
#Expose
private List<Answer> answers = null;
public users(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFacebookId() {
return facebookId;
}
public void setFacebookId(String facebookId) {
this.facebookId = facebookId;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getActivated() {
return activated;
}
public void setActivated(String activated) {
this.activated = activated;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
Basically what happens is when it is called my "message" part comes back "Successful" which on my PHP side basically just states there were no errors. If there were any then it would return the error for display.
When trying to get the users information it always comes back with an empty List.
My response is always the same:
03-14 20:06:26.698 30995-30995/com.josh.testapp D/Response: {"message":"Success","users":[]}
03-14 20:06:26.699 30995-30995/com.josh.testapp I/System.out: Users:: []
03-14 20:06:26.699 30995-30995/com.josh.testapp D/Message: Success
I'm not sure what it is I'm missing. The users should be coming back as a list containing user information, in this case just the information of the user logging in. But in other parts, this will display sub-users information as well which is why it is in List form in the first place.
Please help or guide me in the right direction.
login.java (where the call is made)
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RestInterface.url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestInterface restInterface = retrofit.create(RestInterface.class);
Call<userlogin> call = restInterface.Login(
username.getText().toString(), // username
pass.getText().toString() // password
);
call.enqueue(new Callback<userlogin>() {
#Override
public void onResponse(Call<userlogin> call, retrofit2.Response<userlogin> response) {
if (response.isSuccessful()) {
userlogin ul = response.body();
try{
String res = new Gson().toJson(response.body());
Log.d("Response", res);
System.out.println("Users:: " + ul.getUsers().toString());
Log.d("Message", ul.getMessage().toString());
List<users> userList = ul.getUsers();
for(int i = 0; i < userList.size(); i++){
Log.d("Users", userList.get(i).getUsername());
}
} catch (Exception e){
Log.d("exception", e.getMessage());
}
} else {
Log.d("unSuccessful", response.message());
}
}
#Override
public void onFailure(Call<userlogin> call, Throwable t) {
Log.d("onFailure", t.getMessage());
}
});
After AbdulAli pointed out that it appeared to not be receiving the users list I decided to look over my code and run a few more tests on the server API. I discovered there was an issue with sessions. They weren't picking up and therefor returned a "Successful" yet empty user list. After implementing some CookieJar functions in I was able to pass my cookie for sessions and the user list was no longer empty.
While I feel like an idiot for missing something so obvious, I am very grateful for you pointing that out AbdulAli.

Spring boot REST API Missing URI template variable

I have followed this tutorial to build REST API using Spring boot. It taught alot. But What I am trying to do really got me stuck.
What I am trying to get is:
{
"marks":{
"id":"1",
"name":"test",
"remark":"passed",
"course": {
"id": "1",
"name": "Spring Boot",
"description": "Solves many problems",
"topic": {
"id": "1",
"name": "Java",
"description": "Powerful Programming Language"
}
}
But I get the error when I tried to add the marks- as :
{
"timestamp": 1515600105327,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.web.bind.MissingPathVariableException",
"message": "Missing URI template variable 'courseId' for method parameter of type String",
"path": "/topics/1/courses/1/marks"
}
My Marks Model is:
public class Marks {
#Id
private String id;
private String name;
private String remark;
#ManyToOne
private Course course;
#ManyToOne
private Topic topic;
public Marks() {
}
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
public Marks(String id, String name, String remark,String topicId, String courseId) {
this.id = id;
this.name = name;
this.remark = remark;
this.topic = new Topic(topicId, "","");
this.course = new Course(courseId, " ", " ", " ");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
}
And MarksController.java:
public class MarksController {
#RestController
public class MarksController {
#Autowired
private MarksService marksService;
#RequestMapping("/topics/{topicId}/courses/{id}/marks")
public List<Marks> getAllMarks(#PathVariable String courseId) {
return marksService.getAllMarks(courseId);
}
#RequestMapping(method=RequestMethod.POST, value="/topics/{topicId}/courses{courseId}/marks")
public void addMarks(#RequestBody Marks marks,#PathVariable String topicId ,#PathVariable String courseId) {
marks.setTopic(new Topic(topicId, "", ""));
marks.setCourse(new Course(courseId, "", "", ""));
marksService.addMarks(marks);
}
}
And MarksService.java:
public class MarksService {
#Service
public class MarksService {
#Autowired
private MarksRepository marksRepository;
public void addMarks(Marks marks) {
marksRepository.save(marks);
}
}
And MarksRepository.java:
public interface MarksRepository extends CrudRepository<Marks, String> {
public List<Marks> findByCourseId(String courseId);
public List<Marks> findByTopicId(String topicId);
}
Can anyone help me get the result as in the mentioned JSON.
For the POST method
This:
/topics/{topicId}/courses{courseId}/marks
Should be:
/topics/{topicId}/courses/{courseId}/marks
Note the additional / between courses and {courseId}
For the GET method
This:
/topics/{topicId}/courses/{id}/marks
Should be:
/topics/{topicId}/courses/{courseId}/marks
Note the use of courseId to agree with the parameter name in MarksController.getAllMarks.

Spring REST Jpa HATEOAS links not being created

I know that very similar questions have been asked here before, but I'm struggling to apply it to my problem.
I've recently started using jpa repositories for my data persistence needs and until now i had been content building HAL links that i wanted. Then i found that if i started using the #JoinTable and #JoinColumn annotations then i could have my links generated for me.
My problem is that when i hit the endpoint for my /posts, i don't get a HAL link for comments in the response.
#Entity
#Table(name="post")
public class Post {
#Id
#Column(name="id")
private #JsonIgnore Long id;
#Column(name="text")
private String text;
#Column(name="sender_id")
private Long senderId;
#Column(name="event_id")
private Long eventId;
protected Post () {};
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Long getSenderId() {
return senderId;
}
public void setSenderId(Long senderId) {
this.senderId = senderId;
}
public Long getEventId() {
return eventId;
}
public void setEventId(Long eventId) {
this.eventId = eventId;
}
}
#Entity
#Table(name="comment")
public class Comment {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="id")
private #JsonIgnore Long id;
#Column(name="text")
private String comment;
#JsonIgnore
#Column(name="sender_id")
private Long senderId;
#JsonIgnore
#JoinColumn(name="post_id")
private Long post_id;
#JsonIgnore
#Column(name="deleted")
private Boolean deleted;
#ManyToOne
#JoinTable(name="post")
private Post post;
protected Comment() {};
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Long getSenderId() {
return senderId;
}
public void setSenderId(Long senderId) {
this.senderId = senderId;
}
public Long getPostId() {
return post_id;
}
public void setPostId(Long postId) {
this.post_id = postId;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post
}
}
#RestController
public class CommentController {
private JdbcOperations jdbc;
private final CommentRepository commentDao;
#Autowired
public CommentController(CommentRepository postDao) {
this.commentDao = postDao;
}
#RequestMapping(value = "/comments", method = RequestMethod.GET)
public ResponseEntity<Resources<Resource<Comment>>> getPagedList(#RequestParam(value = "user-id", required = true) long userId,
#RequestParam(value = "page-size", required = false, defaultValue = "20") Long pageSize,
#RequestParam(value = "page", required = false, defaultValue = "1") Long pageNum) {
List<Comment> commentsList = (ArrayList) commentDao.findAll();
List<Resource<Comment>> resourceList = new ArrayList<>();
for (Comment comment : commentsList) {
Resource<Comment> postResource = new Resource<>(comment);
postResource.add(linkTo(methodOn(CommentController.class)
.getPagedList(userId, pageSize,pageNum)).withSelfRel());
resourceList.add(postResource);
}
Resources<Resource<Comment>> resources = new Resources<>(resourceList,
linkTo(methodOn(PostController.class)
.getPagedList(userId, pageSize, pageNum)).withSelfRel());
return ResponseEntity.ok(resources);
}
#RestController
public class PostController {
private final PostRepository postDao;
#Autowired
public PostController(PostRepository postDao) {
this.postDao = postDao;
}
#RequestMapping(value = "/posts", method = RequestMethod.GET)
public ResponseEntity<Resources<Resource<Post>>> getPagedList(#RequestParam(value="user-id", required = true) long userId,
#RequestParam(value = "page-size", required = false, defaultValue = "20") Long pageSize,
#RequestParam(value = "page", required = false, defaultValue = "1") Long pageNum) {
List<Post> modelsList = (ArrayList) postDao.readBydeletedIsFalseOrderByCreated();
List<Resource<Post>> resourceList = new ArrayList<>();
for (Post post : modelsList) {
Resource<Post> resource = new Resource<>(post);
resource.add(linkTo(methodOn(PostController.class)
.getSpecificModel(post.getId())).withSelfRel());
resource.add(linkTo(methodOn(UserController.class).getSpecificModel(post.getSenderId()))
.withSelfRel().withRel("sender"));
if (post.getEventId() != null) {
resource.add(linkTo(methodOn(EventController.class)
.getSpecificModel(post.getEventId())).withSelfRel().withRel("event"));
}
resourceList.add(resource);
}
Resources<Resource<Post>> resources = new Resources<>(resourceList,
linkTo(methodOn(PostController.class)
.getPagedList(userId, pageSize, pageNum)).withSelfRel());
return ResponseEntity.ok(resources);
}
The response i get when i hit the /posts endpoint is this, with no link to comments:
http://localhost:8090/posts?user-id=1
{
"_embedded": {
"postList": [
{
"created": -84330000000,
"text": "second post",
"senderId": 2,
"eventId": null,
"_links": {
"self": {
"href": "http://localhost:8090/posts/2"
},
"sender": {
"href": "http://localhost:8090/users/2"
}
}
},
{
"created": 1286665200000,
"text": "dfgtfy",
"senderId": 1,
"eventId": null,
"_links": {
"self": {
"href": "http://localhost:8090/posts/1"
},
"sender": {
"href": "http://localhost:8090/users/1"
}
}
},
{
"created": 1464735600000,
"text": "third",
"senderId": 1,
"eventId": null,
"_links": {

Categories