Spring Boot + JPA + MySQL 在检索和存储数据时出现500错误 – 内部服务器错误。

huangapple go评论72阅读模式
英文:

Spring Boot + JPA + MySQL getting 500 error Internal Server while retrieving and storing the data

问题

我正在创建Spring API但在创建GET和POST请求时抛出500 HTTP状态码但当我在我的MySQL数据库中检查时数据已经被存储了

**application.properties**

# DataSource settings: set here your own configurations for the database connection.
# In this example we have "javatechie" as database name and
# "root" as username and password.
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/javatechie
spring.datasource.username=root
spring.datasource.password=root
# Show or not log for each sql query
spring.jpa.show-sql=true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto=update
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

**Product.java**

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Product {

    @Id
    @GeneratedValue
    private int id;
    private String name;
    private int quantity;
    private double price;
}

**ProductController.java**

@Controller
public class ProductController {
    @Autowired
    private ProductService productService;

    @PostMapping("/addProduct")
    public Product addProduct(@RequestBody Product product){
        return productService.saveProduct(product);
    }

    @PostMapping("/addProducts")
    public List<Product> addProducts(@RequestBody List<Product> product){
        return productService.saveProducts(product);
    }

    @GetMapping("/products")
    public List<Product> findAllProducts(){
        return productService.getProducts();
    }

    @GetMapping("/product/{id}")
    public Product findProductById(@PathVariable int id){
        return productService.getProductById(id);
    }

    @GetMapping("/product/{name}")
    public Product findProductByName(@PathVariable String name){
        return productService.getProductsByName(name);
    }

    @PutMapping("/update")
    public Product updateProduct(@RequestBody Product product){
        return productService.updateProduct(product);
    }

    @DeleteMapping("/delete/{id}")
    public String deleteProduct(@PathVariable int id){
        return productService.deleteProduct(id);
    }
}

**ProductService.java**

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Product saveProduct(Product product){
        return productRepository.save(product);
    }

    public List<Product> saveProducts(List<Product> products){
        return productRepository.saveAll(products);
    }

    public List<Product> getProducts(){
        return productRepository.findAll();
    }

    public Product getProductById(int id){
        return productRepository.findById(id).orElse(null);
    }

    public Product getProductsByName(String name){
        return productRepository.findByName(name);
    }

    public String deleteProduct(int id){
        productRepository.deleteById(id);
        return "product removed !!!";
    }

    public Product updateProduct(Product product){
        return productRepository.save(product);
    }
}

**错误日志**

2020-09-25 09:25:50.447  INFO 12128 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
Hibernate: select product0_.id as id1_0_, product0_.name as name2_0_, product0_.price as price3_0_, product0_.quantity as quantity4_0_ from product product0_
2020-09-25 09:25:50.613 ERROR 12128 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [products]: would dispatch back to the current handler URL [/products] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause

javax.servlet.ServletException: Circular view path [products]: would dispatch back to the current handler URL [/products] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
    ...

(请注意,代码中的&quot;&lt;等HTML转义字符已被恢复为正常字符。)

英文:

I am creating Spring API but it is throwing 500 HTTP status code while creating GET and POST request but when I have checked in my MySQL database it is storing the data

application.properties

# DataSource settings: set here your own configurations for the database connection.
# In this example we have &quot;javatechie&quot; as database name and
# &quot;root&quot; as username and password.
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/javatechie
spring.datasource.username=root
spring.datasource.password=root
# Show or not log for each sql query
spring.jpa.show-sql=true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto=update
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Product.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private int quantity;
private double price;
}

ProductController.java

@Controller
public class ProductController {
@Autowired
private ProductService productService;
@PostMapping(&quot;/addProduct&quot;)
public Product addProduct(@RequestBody Product product){
return productService.saveProduct(product);
}
@PostMapping(&quot;/addProducts&quot;)
public List&lt;Product&gt; addProducts(@RequestBody List&lt;Product&gt; product){
return productService.saveProducts(product);
}
@GetMapping(&quot;/products&quot;)
public List&lt;Product&gt; findAllProducts(){
return productService.getProducts();
}
@GetMapping(&quot;/product/{id}&quot;)
public Product findProductById(@PathVariable int id){
return productService.getProductById(id);
}
@GetMapping(&quot;/product/{name}&quot;)
public Product findProductByName(@PathVariable String name){
return productService.getProductsByName(name);
}
@PutMapping(&quot;/update&quot;)
public Product updateProduct(@RequestBody Product product){
return productService.updateProduct(product);
}
@DeleteMapping(&quot;/delete/{id}&quot;)
public String deleteProduct(@PathVariable int id){
return productService.deleteProduct(id);
}
}

ProductService.java

@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public Product saveProduct(Product product){
return productRepository.save(product);
}
public List&lt;Product&gt; saveProducts(List&lt;Product&gt; products){
return productRepository.saveAll(products);
}
public List&lt;Product&gt; getProducts(){
return productRepository.findAll();
}
public Product getProductById(int id){
return productRepository.findById(id).orElse(null);
}
public Product getProductsByName(String name){
return productRepository.findByName(name);
}
public String deleteProduct(int id){
productRepository.deleteById(id);
return &quot;product removed !!!&quot;;
}
public Product updateProduct(Product product){
return productRepository.save(product);
}
}

Note :-
When I send a POST request from Postman it is throwing me

{
&quot;timestamp&quot;: &quot;2020-09-24T20:01:15.060+00:00&quot;,
&quot;status&quot;: 500,
&quot;error&quot;: &quot;Internal Server Error&quot;,
&quot;message&quot;: &quot;&quot;,
&quot;path&quot;: &quot;/addProduct&quot;
}

but when I have checked in the MySQL database the entries which I had send through POST request those are there

Spring Boot + JPA + MySQL 在检索和存储数据时出现500错误 – 内部服务器错误。

Question

  1. Why I am getting HTTP status code 500 error ??
  2. Even I am getting the error then how data is getting the store in the database ??
  3. If I am successfully storing the data in database then why am not getting through GET request ??

Error Logs

2020-09-25 09:25:50.447  INFO 12128 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
Hibernate: select product0_.id as id1_0_, product0_.name as name2_0_, product0_.price as price3_0_, product0_.quantity as quantity4_0_ from product product0_
2020-09-25 09:25:50.613 ERROR 12128 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [products]: would dispatch back to the current handler URL [/products] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause
javax.servlet.ServletException: Circular view path [products]: would dispatch back to the current handler URL [/products] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:210) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:148) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.38.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.38.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]

答案1

得分: 3

  1. 为什么我会得到HTTP状态码500错误?
    => 你得到500错误是因为你的控制器需要一个视图模板(比如Thymeleaf、JSP或其他视图引擎)。
  2. 即使我在得到错误,数据是如何存储在数据库中的?
    => 只有在渲染时出现问题,数据仍然会被持久化存储在数据库中,这就是为什么它存储在你的数据库中。
  3. 如果我成功地将数据存储在数据库中,为什么不能通过GET请求获得数据?
    => 因为你的GET控制器仍然需要一个视图模板。

如果你正在开发RESTful API,可以使用@RestController或在每个控制器端点方法上添加@ResponseBody。

顺便说一句,你不应该使用实体来处理请求体。

英文:
  1. Why I am getting HTTP status code 500 error ??
    => You get 500 because your controller needs a view template (such as thymeleaf, JSP or whatever view engine)
  2. Even I am getting the error then how data is getting the store in the database ??
    => You're having issue only when rendering not persist data, that why It's stored in your DB
  3. If I am successfully storing the data in database then why am not getting through GET request ??
    => Because your GET Controller still needs a view template.

If you're developing Restful APIs then using @RestController or add @ResponseBody on each controller endpoint method.

Btw, you're should not use an Entity to handle your Request body.

答案2

得分: 0

请显示服务器日志。仅凭服务器响应无法弄清楚。将控制器用 try/catch 包围起来,并打印异常。

英文:

Please show the server log. Only with the server response it's impossible to figure out. Surround the controller with try/catch and print the exception

答案3

得分: -2

只需创建一个空的默认构造函数。

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Product {

    @Id
    @GeneratedValue
    private int id;
    private String name;
    private int quantity;
    private double price;

    // 在下面添加这个

    public Product() {
    }
}
英文:

Simply create an empty default constructor.

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private int quantity;
private double price;
//this one below
public Product()
{
}

huangapple
  • 本文由 发表于 2020年9月25日 04:19:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64053846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定