Issue
I want to get Mutual-friend
from database, query and all code work well but get weird response from controller AbstractJpaQuery$TupleConverter$TupleBackedMap@7db3be92
. I can pass List<DTO>
in controller as return type. I want to get username
and other more column from database.
Here down is my code:
DTO
public interface ProfileJoin {
public Integer getU_id();
public String getUsername();
public String getPassword();
}
Query In Repository
@Query(nativeQuery = true, value="SELECT Distinct rgm.username, rm1.sender_id, rm1.receiver_id, pm.profile FROM registration_master as rgm INNER JOIN profile_master AS pm ON rgm.u_id = pm.user_id INNER JOIN request_master AS rm1 ON rgm.u_id = rm1.receiver_id INNER JOIN request_master AS rm2 ON rgm.u_id = rm2.receiver_id WHERE rm1.sender_id = ? AND rm1.status = ? AND rm2.sender_id = ? AND rm2.status = ?")
List<ProfileJoin> getMutualFriend(Integer Sender_id1, String Status1, Integer Sender_id2, String Status2);
Controller
@RequestMapping(value="/getmutualfriend/{id}", method = RequestMethod.GET)
public void getMutualFriend(HttpServletRequest req, HttpServletResponse res, HttpSession session, @PathVariable("id") Integer id) throws IOException
{
List<ProfileJoin> getMutualFriend = service.getMutualFriend(Integer.parseInt(session.getAttribute("uid").toString()), "Accept", id, "Accept");
if(getMutualFriend.size() > 0)
{
res.getWriter().print(getMutualFriend);
}
else
{
res.getWriter().print(" ");
}
}
AJAX
$(document).ready(function(){
$.ajax({
type: "GET",
url: "/getmutualfriend/" + $("#friend_ID").attr("value"),
success: function(res){
console.log(res)
}
});
});
My Output
Expected Output
I get perfect output when get Mutual-friend
without using ajax...
Solution
Writing data directly to the Response: res.getWriter().print(getMutualFriend);
this will write the result of the toString()
call on your object...
You should return the actual data: List<ProfileJoin>
@RequestMapping(value="/getmutualfriend/{id}", method = RequestMethod.GET)
@ResponseBody // <--- will write result as json in the resoponse
public List<ProfileJoin> getMutualFriend(HttpServletRequest req, HttpServletResponse res, HttpSession session, @PathVariable("id") Integer id) throws IOException
{
return service.getMutualFriend(Integer.parseInt(session.getAttribute("uid").toString()), "Accept", id, "Accept");
}
Then you can access the data via your JS
$(document).ready( function() {
$.ajax({
url: "/getmutualfriend/" + $("#friend_ID").attr("value"),
type: "GET",
success: function(data) {
for (var i = 0; i < data.length; i++) {
console.log(data[i].u_id);
console.log(data[i].username);
}
}
});
});
Answered By - Dirk Deyne