I am using hibernate with spring boot. I want to get next and previous record from table by passing an id. I have written a query in hql to get next and previous records from table. The problem is that i am getting all previous and all next records but i want only one previous and one last record.
Here is my DAO class for next record
@Transactional
public interface DataDao extends CrudRepository<Data, Long> {
@Query(getDataId)
NextPrevData getDataId(Long post_id, Long data_id);
final String getDataId= "select new netgloo.models.NextPrevData(d.id) from Data d where d.postId=?1 and d.id>?2";
}
Here is DAO for previous record
@Transactional
public interface PrevDao extends CrudRepository<Data, Long> {
@Query(getDataId)
NextPrevData getDataId(Long post_id, Long data_id);
final String getDataId= "select new netgloo.models.NextPrevData(d.id) from Data d where d.postId=?1 and d.id<?2";
}
Here is my Controller
@RequestMapping("/{post_id}/{data_id}")
@ResponseBody
public Next getDataInfo(@PathVariable("post_id") long post_id, @PathVariable("data_id") long data_id, HttpServletRequest req, HttpServletResponse res) throws ServletException {
NextPrevData Next = dataDao.getDataId(post_id, data_id);
NextPrevData Prev = prevDao.getDataId(post_id, data_id);
Post2 postobj = postDao2.findOne(post_id);
Data d = dataDao.findOne(data_id);
if(Next.isEquals(null)){
postobj.setNextStatus(false);
}
else{
postobj.setNextStatus(true);
}
if(Prev.isEmpty()){
postobj.setPrevStatus(false);
}
else{
postobj.setPrevStatus(true);
}
return new Next(Next,postobj,Prev,d);
}
Here is myNext class
public class Next {
private NextAndPrevious Next;
private NextAndPrevious Prev;
private Post2 post;
private Data d;
public Post2 getPost() {
return post;
}
public void setPost(Post2 post) {
this.post = post;
}
public Next(NextAndPrevious Next, Post2 postobj, NextAndPrevious Prev, Data d) {
this.Next = Next;
this.post = postobj;
this.Prev = Prev;
this.d = d;
}
//Getters and seters