Got status 500 and message "Missing URI template variable 'rank'", whenever test HTTP POST request on postman - spring-boot

I got the error "Resolved [org.springframework.web.bind.MissingPathVariableException: Missing URI template variable 'rank' for method parameter of type Rank]" on eclipse console
And message: "Missing URI template variable 'rank' for method parameter of type Rank" with status "500" whenever try HTTP POST request
My RESTController code:
#RestController
#RequestMapping(path = "/comp")
public class RankController {
#PostMapping(path = "/rank")
ResponseEntity<Rank> createRank(#Valid #PathVariable Rank rank) throws URISyntaxException{
Rank result = rankRepository.save(rank);
return ResponseEntity.created(new URI("/comp/rank" + result.getId())).body(result);
}
}
My Rank entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "RANK_TBL")
public class Rank {
#Id
private Long id;
private String name;
#ManyToOne(cascade = CascadeType.PERSIST)
private Employee employee;
}
My Employee entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "EMPLOYEE_TBL")
public class Employee {
#Id
private Long id;
private String name;
private String email;
#OneToMany
private Set<Rank> Rank;
}

Change #PathVariable with #RequestBody
Here you are making a request to save the entity and you should pass the payload as #RequestBody in JSON format. From postman you may use raw type and select the JSON type.
Ideal way is to use #RequestBody whenever we are creating or updating the records which requires the object to passed with POST and PUT methods. For methods which retrieves the records based on Id or some parameters you may use #PathVariable
You may explore more about the annotations here

Related

Webclient call returns entity ID with null value when the other part correctly

I use WebClient to make calls between services by using Spring boot and Java 11. However, I receive the response entity with a null ID and the other parts have valid values. Whereas I have another call (WebClient) for another service and I receive the correct
response. How can I fix this issue in order to receive also the ID
#Getter
#Setter
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class Customer {
#JsonProperty("customer_id")
private Integer customerID;
private String name;
private String surname;
private Integer balance;
}
final String CUSTOMER_BASE_URL = "http://CUSTOMER-SERVICE/api/v1";
Customer customer = webClient.baseUrl(CUSTOMER_BASE_URL).build().get().uri("/customer/1")
.retrieve().toEntity(Customer.class).block().getBody();
Response:
customerID = null
name = "Renos"
surname = "Bardis"
balance = {Integer#16157} 100

Spring Boot List of Object Bean Validation

I have a Bean,
#Data
#NoArgsConstructor
public final class PersonRequest {
#NotNull
#JsonProperty("nameList")
private List<Person> nameList;
}
and Person POJO,
#Data
public class Sensor {
#NotNull
#JsonProperty("id")
private int id;
#NotNull
#JsonProperty("name")
#Min(1)
private String name;
}
I am sending JSON request and added #Valid in my controller. I am sending request as below,
{
"nameList": [
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Alex"
}
]
}
When i send request without id and name not validating. I tried using #Valid private List<Person> nameList; also but no luck. I use Spring boot 2.3.2.
UPDATED:
when i add one more attribute, this also say bad request when i pass date in request.
#NotNull
#JsonProperty("startTime")
#DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss", iso =
DateTimeFormat.ISO.DATE_TIME)
#Valid
private LocalDateTime startTime;
The #Valid annotation in your controller triggers the validation of the PersonRequest object, passed as request body. To validate also the Person objects contained in PersonRequest, you need to annotate that field with #Valid too.
#Data
#NoArgsConstructor
public final class PersonRequest {
#NotNull
#JsonProperty("nameList")
#Valid
private List<Person> nameList;
}

How to post an Image and JSON object with single request to back end Spring Boot

I want to send image and JSON data to my back end in Spring Boot.
This is my method:
#PostMapping
public void uploadFile(#ModelAttribute FileUploadDto fileUploadDto) {
My FileUploadDto model:
public class FileUploadDto {
private MultipartFile file;
private CategoryModel category;
My CategoryModel model:
#Entity
#Table(name = "Category")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CategoryModel {
#Id
#Column(name = "id")
//#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String category_name;
private String category_description;
private String image_path;
#JsonIgnore
#OneToMany( mappedBy = "category")
private Set<ProductModel> category;
I do not understand where I'm wrong.
My postman request:
Your payload has to be raw and in json form. Something like this would help Spring boot to convert your payload into a object of an example class:
public class Foo{
public String foo;
public String foo1;
//Getters setters
}
And the request handling method:
#PostMapping
public void uploadFile(#RequestBody Foo foo)
It is also recommended to parse the payload into some a temporary class and then convert objects of the temporary class into the Entity class and vice versa. Take a look at: https://struberg.wordpress.com/2012/01/08/jpa-enhancement-done-right/ for more information
Also, if you want to upload file per REST I also recommend you to take a look at the following documentation: https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
Best luck.

Response Entity not getting mapped for custom objects inside a class

I am hitting an API and getting the response using resttemplate.exchange object and i am mapping the response to a parameterized object .All the variables inside the response class are getting mapped to the response entity object but not the Attribute class variables inside the parameterized object.
ResponseEntity<ArrayList<Response>> responseEntity =
restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
new HttpEntity<>(headers),
new ParameterizedTypeReference<ArrayList<Response>>()
{});
#Getter
#Setter
public class Response {
private String number;
private String id;
private String name;
#JsonProperty("attributes")
private ArrayList<Attributes> attributes ;
}
#Getter
#Setter
#JsonIgnoreProperties(ignoreUnknown=true)
public class Attributes {
private String value;
private String name;
}

How to add One to One relationship with an Embeddable

Requirement:
To fetch the list of requests along with the requests feedback status.
What I'm doing now :
Fetch all the requests using JPQL query. Loop through each request and fetch status and set into response dto.
What I want to doing.
Fetch all the request along with the status using JPQl query
What I'm looking for :
How can I add one to one mapping for requests & status, so that I can fetch status.
Sample code
This is the MSREQUEST entity
#Entity
#Table(name = "MSREQUEST")
public class Request implements Serializable {
#Id
private long requestId;
#Column(name = "DESC")
private string desc;
//getter.. setter...tostring and hashcode
}
This is the status entity
#Entity
#Table(name="FEEDBACKSTATUS")
public class FeedbackStatus implements Serializable {
// composite-id key
#EmbeddedId
private RequestFeedBackId requestFeedbackKey = new RequestFeedBackId();
#Column(name="STATUS")
private Long status;
//getter.. setter...tostring and hashcode
}
This is the embeddable entity
#Embeddable
public class RequestFeedBackId implements Serializable {
#Column(name="REQUESTID")
private Long requestId;
#Column(name="FEEDBACKID")
private Long feedbackId;
}
Service
#Override
public List<MsaRequestSearchDto> searchMsaRequests(MsaRequestSearchDto msaRequestSearchDto)
throws MsaException, Exception {
List<MsaRequestSearchDto> msaRequestSearchDtoList = msaRequestRepoCustom.findMsaRequests(msaRequestSearchDto);
*// get feedback status loop thru and fetch status for each one. nee to avoid this
if(msaRequestSearchDtoList != null && msaRequestSearchDtoList.size() > 0){
// code to fetch dstatus
}*/
return msaRequestSearchDtoList;
}
JPQL query that Im using..
public String GET_MSA_REQUEST = "SELECT dsr FROM Request dsr WHERE 1=1";
E-R

Resources