Search code examples
springspring-bootresttemplate

Error in postman while fetching data from another service using resttemplate


I am having an error in postman while fetching data from another service using RestTemplate.

I have two services. First service have userdetails entity class and second service have posts entity class. This is the code of post controller.

@GetMapping("/findpostbyareacode/{areacode}")
List<Posts> getPostByAreacode(@PathVariable(value="areacode") Long areacode){

    RestTemplate restTemplate=new RestTemplate();

    ResponseEntity<List<UserDetails>> response= 
            restTemplate.exchange("http://localhost:8091/voiceofbengal/userdetailsbyareacode/"+areacode, HttpMethod.GET,
                    null, new ParameterizedTypeReference<List<UserDetails>>(){

    });

    List<UserDetails> body=response.getBody();
    List<Posts> postList=new ArrayList<>();
    List<Posts> totalPost=new ArrayList<>();
    for(UserDetails users : body) {
        totalPost=postService.findByU_id(users.getU_id());
        for(Posts posts : totalPost) {
            postList.add(posts);
        }
    }

    return postList;

}

I am getting this error in postman.

"timestamp": "2019-01-17T09:10:32.977+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Error while extracting response for type [java.util.List<com.css.vob.model.UserDetails>] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String \"01-01-1990\": not a valid representation (error: Failed to parse Date value '01-01-1990': Cannot parse date \"01-01-1990\": not compatible with any of standard forms (\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\", \"yyyy-MM-dd'T'HH:mm:ss.SSS\", \"EEE, dd MMM yyyy HH:mm:ss zzz\", \"yyyy-MM-dd\")); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String \"01-01-1990\": not a valid representation (error: Failed to parse Date value '01-01-1990': Cannot parse date \"01-01-1990\": not compatible with any of standard forms (\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\", \"yyyy-MM-dd'T'HH:mm:ss.SSS\", \"EEE, dd MMM yyyy HH:mm:ss zzz\", \"yyyy-MM-dd\"))\n at [Source: (PushbackInputStream); line: 1, column: 57] (through reference chain: java.util.ArrayList[0]->com.css.vob.model.UserDetails[\"dob\"])",

Edit- After trying @Pijotrek's sollution I am getting this error now.

"message": "could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet"

Here is my entity class, DAO, and JPARepository

This is entity class of UserDetails

And here is the Controller method of user details which I have been calling from post controller-

    @GetMapping("/userdetailsbyareacode/{areacode}")
public ResponseEntity<List<UserDetails>> getUserByAreacode(@PathVariable(value="areacode") Long areacode){
    List<UserDetails> user=userdetailsService.getuserByAreacode(areacode);

    if(user==null) {
        return ResponseEntity.notFound().build();
    }
    return ResponseEntity.ok().body(user);
}

Here is the JPARepository of post controller-

public interface PostRepository extends JpaRepository<Posts,Long> {

@Transactional
@Query(nativeQuery=true,value="SELECT * FROM POSTS WHERE U_ID=:u_id")
List<Posts> findPostsByU_id(@Param("u_id") Long u_id);

Solution

  • You send a body in your request with some user details.

    ResponseEntity<List<UserDetails>> response= restTemplate.exchange("http://localhost:8091/voiceofbengal/userdetailsbyareacode/"+areacode, HttpMethod.GET,
    null, new ParameterizedTypeReference<List<UserDetails>>(){
    });
    

    Reading the error I assume your UserDetails class has a field called dob. The REST API you are reaching in your Controller class (which is a bad practice by the way) tries to convert that dob field and gets an exception because it is not written in any of the accepted formats. Accepted formats are: (\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\", \"yyyy-MM-dd'T'HH:mm:ss.SSS\", \"EEE, dd MMM yyyy HH:mm:ss zzz\", \"yyyy-MM-dd\"));. It's all in your error message. So format your dob like "1990-01-01T10:00:00.000Z" or "1990-01-01" and it should work just fine.

    Alternatively, if you control the REST API you're calling in your Controller, you can use @DateTimeFormat annotation to match the format you send at the moment, i.e: @DateTimeFormat(pattern = "dd-MM-yyyy")

    edit

    Your return type is wrong for executing native query. Anyway, you do not have to use one, you can change your method name to following:

    @Transactional
    List<Posts> findPostsByUserId(Long id);
    

    and that should do the trick