Home > Back-end >  Java: wrapping one entity class in another entity class
Java: wrapping one entity class in another entity class

Time:08-16

i was trying to pass two parameters into the rest template execute method in the request GET body.

The API passes two parameter values

http://localhost:8080/api/likes/user?likes=xyz&user=abc

There are two entity class

public class Account{
public String user;
public String date;
public List<PostList> post;}

And PostList entity class

public class PostList{
public int likes;
public String comment;
public int shares;
}

I want to pass user from the Account class and Likes from Post_List class in the request get call

How could I wrap that in a class and pass the value?

public List<Account> getRatingViaApi(......//wrapper class){
    
        RestTemplate restTemplate = new RestTemplate();

        //String resourceUrl = "http://localhost:8080/movies";
    
        
        RequestCallback requestCallback = request -> {
            ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(request.getBody(), 
                        //Wrapper class);

                request.getHeaders()
                 .setAccept(Arrays.asList(
                         MediaType.APPLICATION_OCTET_STREAM, 
                         MediaType.ALL));
                };

        
        ResponseExtractor<List<Account>> responseExtractor = response -> 
ObjectMapper mapper= new ObjectMapper ();

                return mapper.readValue(response.getBody(),new TypeReference<List<Account>>(){});
             };

        restTemplate.execute(resourceUrl, 
            HttpMethod.GET, 
            requestCallback, 
            responseExtractor );    
}

If there exist a post

[
 {
  "user":"o1",
  "date":"01-03-2022",
  "post":[
        {
       "likes":"1",
       "comment":"abdc",
       "shares":"5"
       }
    ]
 }
]

If there exist no post

[
 {
  "user":null
  "date":null
  "post":null
 }
]

I check these return values

CodePudding user response:

Can have a method to create the url with updated query params. Keeping it simple, can look something like such:

private String createUrlForUserLikes(final Account account, final PostList postList) {
    return String.format("http://localhost:8080/api/likes/user?likes=%s&user=%s", postList.likes(), account.user());
}
  • Related