REST API call: Missing URI template variable 'productoId' for method parameter of type Long - spring

Im trying to do a query in Spring boot to database (http://localhost:8180/products/2) and the server responds with:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 26 01:29:12 COT 2017 There was an unexpected error
(type=Internal Server Error, status=500). Missing URI template
variable 'productoId' for method parameter of type Long
This the interface
package com.beitech.orders.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.beitech.orders.model.Product;
public interface ProductJpaRepository extends JpaRepository<Product, Long> {
Product findByProductoId(Long productoId);
#Query(value = "SELECT * FROM PRODUCT WHERE PRODUCTO_ID = ?1", nativeQuery = true)
Product findByproductoId3(Long productoId);
}
This is the controller:
package com.beitech.orders.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.beitech.orders.model.Product;
import com.beitech.orders.repository.ProductJpaRepository;
#RestController
#RequestMapping("/products")
public class ProductController {
#Autowired
private ProductJpaRepository productJpaRepository;
#GetMapping(value = "/allProducts")
public List<Product> findAll(){
return productJpaRepository.findAll();
}
#GetMapping(value = "/{productId}")
public Product findByProductoId(#PathVariable final Long productoId){
return productJpaRepository.findByProductoId(productoId);
}
}

You defined
#GetMapping(value = "/{productId}")
#PathVariable final Long productoId){
There is a mismatch there between productId and productoId. If you want productId to be bound to Long productoId then you would have to declare #PathVariable(name="productId") or alternatively just rename productoId to productId or vice versa.

Related

springbroot 404 when using multi-modei

I want set two different tables.i have try this first model with corresponding service,controller and respository.Everythings is fine but when i use the same code with only changing the model,and develop a set of service,controller and respository.It cannot show what i expected.
my model:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
#Data
#AllArgsConstructor
#NoArgsConstructor
#javax.persistence.Entity
#Table(schema = "order")
public class Order {
#Id
#GeneratedValue
private int id;
private String product_name;
private int quantity;}
mycontroller:
package com.javatechie.trymysql.contoller;
import com.javatechie.trymysql.Entity.Order;
import com.javatechie.trymysql.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class OrderController {
#Autowired
private OrderService service;
#PostMapping("/add/orders")
public List<Order> addOrders(#RequestBody List<Order> orders){
return service.saveOrders(orders);
}
}
service:
package com.javatechie.trymysql.service;
import com.javatechie.trymysql.Entity.Order;
import com.javatechie.trymysql.repository.OrderRepository;
import com.javatechie.trymysql.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class OrderService {
#Autowired
private OrderRepository Repository;
public List<Order> saveOrders(List<Order> order) {
return Repository.saveAll(order);
}
}
repository:
package com.javatechie.trymysql.repository;
import com.javatechie.trymysql.Entity.Order;
import com.javatechie.trymysql.Entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface OrderRepository extends JpaRepository<Order,Integer> {
}
my ide pattern is like:
com.javatechie.trymysql
-entity
--Product
--Order
-controller
--productcontroller
--ordercontroller
-service
--productservice
--orderservice
-repository
--productrespository
--orderreposiory
-productconfig
-Trymysqlapplication
Postman request:
[{
"proudct_name":"sand",
"quantity":5
},{
"product_name":"fruit",
"quantity":2
}]
error:
{
"timestamp": "2022-10-17T13:14:03.284+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/add/orders"
}
Everytime i run the server it display the following log:
Hibernate: select product0_.id as id1_1_0_, product0_.name as name2_1_0_, product0_.price as price3_1_0_, product0_.quantity as quantity4_1_0_ from product_tbl product0_ where product0_.id=?
Hibernate: select product0_.id as id1_1_0_, product0_.name as name2_1_0_, product0_.price as price3_1_0_, product0_.quantity as quantity4_1_0_ from product_tbl product0_ where product0_.id=?
But it still works fine
later i add the second table it just show me:
Hibernate: select order0_.id as id1_0_0_, order0_.product_name as product_2_0_0_, order0_.quantity as quantity3_0_0_ from order order0_ where order0_.id=?
2022-10-17 21:21:11.916 WARN 3828 --- [nio-9191-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000
i dont why my log file automatically generate this sql and got the error when it is not the model "product"?
I dont know which step i have done wrong when trying using the second model(order)
Extracted details from comments.
As you have table name order which is a reserved keyword in MySQL. So you have to change the table name to another name that is not a reserved keyword. Change to orders resolves the issue.

Spring boot -Whitelabel Error Page Local host

I have set up my request controller and rest mapping but I am receiving 'Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Mar 11 20:28:19 GMT 2022
There was an unexpected error (type=Not Found, status=404).
No message available' when I use the url http://localhost:8080/hello .
It was working a week ago. I have the correct dependency and I have tried component scan base package in my app.java and moving the controller to the same package as the app.java. Ive attached my package explorer and below is my code
package com.fyp.reviewchecker.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class SearchController {
#RequestMapping("/hello") public String hello() {
return "Hello\n";
}
}
package com.fyp.reviewchecker;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.jdbc.core.JdbcTemplate;
#SpringBootApplication
#EnableJpaAuditing
public class ReviewcheckerApplication implements CommandLineRunner {
#Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(ReviewcheckerApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
String sql = "INSERT INTO contact_table (name, subject, message, email, phone) VALUES ( ?, ?, ?, ?, ? ) ";
int result = jdbcTemplate.update(sql, "kirsty", "Complaint", "Love it", "Kirstenlivs#gmail.com", "07429");
if (result > 0) {
System.out.println("contact form updated");
}
}
}
package explorer
first avoid using #RequestMapping use #PostMapping, #GetMapping etc
instead.
check if you have configuration in your property files like this:
server.servlet.context
to check if the controller is being scanned by spring or not, you can try using applicationContext.getBeansOfType(SearchController.class); in your main/commandLineRunner or by using a #PostConstruct in the SearchController with some logging in the console.
It was nothing to do with my code I had a 'missing' Jar file that I hadn't disposed of properly so my project wouldn't build until I had it. I added the jar file back and deleted it and now it works.

In Spring boot application is #Component annotation optional for repo

I have created the basic application using Spring boot using JPA. I have added #AutoWired annotation for RatingRepo in RatingResource, but haven't added #Component annotation to RatingRepo
package com.example.demo;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.RatingsRateService.model.Rating;
import com.example.demo.RatingsRateService.model.UserRating;
#RestController
#RequestMapping("ratingsdata")
public class RatingResource {
#Autowired
RatingRepo repo;
/*
* #RequestMapping("/{movieId}") public Rating
* getRating(#PathVariable("movieId") String movieId) { return new
* Rating(movieId,7); }
*/
#RequestMapping("users/{userid}")
public UserRating getRating(#PathVariable("userid") int userid) {
List<Rating> ratings =repo.findByUserId(userid);
/*
* List<Rating> ratings = Arrays.asList(new Rating("1",4), new Rating("2",3),
* new Rating("3",2));
*/
System.out.println(ratings);
UserRating userRating = new UserRating();
userRating.setUserRating(ratings);
return userRating;
}
}
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.example.demo.RatingsRateService.model.Rating;
//to update the data in database , created the interd=face and will implement
//class,primary key
public interface RatingRepo extends JpaRepository<Rating, Integer>{
#Query(" from Rating where userid = ?1")
List<Rating> findByUserId( int userid);
}
. Still, it is working fine. Can you someone please explain why it is so? Or it is not needed to add #Component annotation for the repo?
first of there is #Repository annotation required not #Component
and #Repository also auto configure due to below:
Probably you are using spring boot
Spring Data repositories usually extend from the Repository or CrudRepository interfaces. If you are using auto-configuration, repositories will be searched from the package containing your main configuration class (the one annotated with #EnableAutoConfiguration or #SpringBootApplication) down.
ref: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-spring-data-jpa-repositories

how to request data from our spring boot micro-service to external server for a given id's?

Currently I have created 2 microservices and and getting the data from one service to another using RestTemplate.
Microservice -1:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
#RestController
public class StringDataController {
List<String> stringList = new ArrayList<>();
#RequestMapping(value = "/securities/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> sendStringData(){
stringList.add("12345");
stringList.add("23435");
stringList.add("23436");
return stringList;
}
}
Microservice-2:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
#RestController
#EnableAutoConfiguration
public class ExternalRequestController {
#Value ("${sampleMS1.uri}")
String sampleMS1URI;
#RequestMapping(value="/listdata", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void receiveStringFromAnotherMS(){
List<String> list = null;
list = new RestTemplate().getForObject(sampleMS1URI,List.class);
System.out.println(list.toString());
System.out.println("-->"+list);
}
}
Now, I have to send the List(String)(list of ID's) data to some external server and response should get Map(K,V) ==> key as a String and Value as a Double.
Note: The external server is not handling by us, so we can only request the data with List of id's and then they should sending the response with price data of specific id's.
Can anyone suggest me a way to do it ?
I am new to Spring & Spring boot.
Thank you!

In spring boot project, When I click submit button, how can I solve Whitelabel Error Page Error,

When I click on submit button I got this error message
Whitelabel Error Page This application has no explicit mapping for
/error, so you are seeing this as a fallback. Tue Jun 30 17:24:02 CST
2015 There was an unexpected error (type=Not Found, status=404). No
message available
Here is my code.
package com.tourpackage.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tourpackage.model.TourPackage;
import com.tourpackage.repository.TourPackageMongoRepository;
import com.tourpackage.repository.VehicleTypeMongoRepository;
#Controller
public class TourPackageController {
#Autowired
TourPackageMongoRepository packageRepository;
VehicleTypeMongoRepository vehicleTypeRepository;
#RequestMapping("/tourpackage")
public String tourpackage(Model model){
model.addAttribute("packagelist", packageRepository.findAll());
return "index";
}
#RequestMapping("/addNewTour")
public String addNewTour(Model model){
model.addAttribute("packagelist", packageRepository.findAll());
return "tourpack";
}
#RequestMapping(value="/addPackage", method = RequestMethod.POST)
public String addPackage(#ModelAttribute TourPackage tourpack) {
packageRepository.save(tourpack);
return "redirect:tourpackage";
}
}
Spring Boot automatically registers the Basic ErrorController as a Spring Bean when you haven't specified an implementation for ErrorController.
so,
If you want to return customised content for path /error, refer following code:
#RestController
public class MyController implements ErrorController{
private static final String PATH = "/error";
#RequestMapping(value = PATH)
public String error() {
return "Error handling";
}
#Override
public String getErrorPath() {
return PATH;
}
}
Else,
If you want to disable it, you can refer this post:
http://www.logicbig.com/tutorials/spring-framework/spring-boot/disable-default-error-page/

Resources