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

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

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

问题

  1. 我正在创建Spring API但在创建GETPOST请求时抛出500 HTTP状态码但当我在我的MySQL数据库中检查时数据已经被存储了
  2. **application.properties**
  3. # DataSource settings: set here your own configurations for the database connection.
  4. # In this example we have "javatechie" as database name and
  5. # "root" as username and password.
  6. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  7. spring.datasource.url=jdbc:mysql://localhost:3306/javatechie
  8. spring.datasource.username=root
  9. spring.datasource.password=root
  10. # Show or not log for each sql query
  11. spring.jpa.show-sql=true
  12. # Hibernate ddl auto (create, create-drop, update)
  13. spring.jpa.hibernate.ddl-auto=update
  14. # The SQL dialect makes Hibernate generate better SQL for the chosen database
  15. spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
  16. **Product.java**
  17. @Data
  18. @AllArgsConstructor
  19. @NoArgsConstructor
  20. @Entity
  21. public class Product {
  22. @Id
  23. @GeneratedValue
  24. private int id;
  25. private String name;
  26. private int quantity;
  27. private double price;
  28. }
  29. **ProductController.java**
  30. @Controller
  31. public class ProductController {
  32. @Autowired
  33. private ProductService productService;
  34. @PostMapping("/addProduct")
  35. public Product addProduct(@RequestBody Product product){
  36. return productService.saveProduct(product);
  37. }
  38. @PostMapping("/addProducts")
  39. public List<Product> addProducts(@RequestBody List<Product> product){
  40. return productService.saveProducts(product);
  41. }
  42. @GetMapping("/products")
  43. public List<Product> findAllProducts(){
  44. return productService.getProducts();
  45. }
  46. @GetMapping("/product/{id}")
  47. public Product findProductById(@PathVariable int id){
  48. return productService.getProductById(id);
  49. }
  50. @GetMapping("/product/{name}")
  51. public Product findProductByName(@PathVariable String name){
  52. return productService.getProductsByName(name);
  53. }
  54. @PutMapping("/update")
  55. public Product updateProduct(@RequestBody Product product){
  56. return productService.updateProduct(product);
  57. }
  58. @DeleteMapping("/delete/{id}")
  59. public String deleteProduct(@PathVariable int id){
  60. return productService.deleteProduct(id);
  61. }
  62. }
  63. **ProductService.java**
  64. @Service
  65. public class ProductService {
  66. @Autowired
  67. private ProductRepository productRepository;
  68. public Product saveProduct(Product product){
  69. return productRepository.save(product);
  70. }
  71. public List<Product> saveProducts(List<Product> products){
  72. return productRepository.saveAll(products);
  73. }
  74. public List<Product> getProducts(){
  75. return productRepository.findAll();
  76. }
  77. public Product getProductById(int id){
  78. return productRepository.findById(id).orElse(null);
  79. }
  80. public Product getProductsByName(String name){
  81. return productRepository.findByName(name);
  82. }
  83. public String deleteProduct(int id){
  84. productRepository.deleteById(id);
  85. return "product removed !!!";
  86. }
  87. public Product updateProduct(Product product){
  88. return productRepository.save(product);
  89. }
  90. }
  91. **错误日志**
  92. 2020-09-25 09:25:50.447 INFO 12128 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 10 ms
  93. 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_
  94. 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
  95. 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.)
  96. ...

(请注意,代码中的&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

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

Product.java

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. @Entity
  5. public class Product {
  6. @Id
  7. @GeneratedValue
  8. private int id;
  9. private String name;
  10. private int quantity;
  11. private double price;
  12. }

ProductController.java

  1. @Controller
  2. public class ProductController {
  3. @Autowired
  4. private ProductService productService;
  5. @PostMapping(&quot;/addProduct&quot;)
  6. public Product addProduct(@RequestBody Product product){
  7. return productService.saveProduct(product);
  8. }
  9. @PostMapping(&quot;/addProducts&quot;)
  10. public List&lt;Product&gt; addProducts(@RequestBody List&lt;Product&gt; product){
  11. return productService.saveProducts(product);
  12. }
  13. @GetMapping(&quot;/products&quot;)
  14. public List&lt;Product&gt; findAllProducts(){
  15. return productService.getProducts();
  16. }
  17. @GetMapping(&quot;/product/{id}&quot;)
  18. public Product findProductById(@PathVariable int id){
  19. return productService.getProductById(id);
  20. }
  21. @GetMapping(&quot;/product/{name}&quot;)
  22. public Product findProductByName(@PathVariable String name){
  23. return productService.getProductsByName(name);
  24. }
  25. @PutMapping(&quot;/update&quot;)
  26. public Product updateProduct(@RequestBody Product product){
  27. return productService.updateProduct(product);
  28. }
  29. @DeleteMapping(&quot;/delete/{id}&quot;)
  30. public String deleteProduct(@PathVariable int id){
  31. return productService.deleteProduct(id);
  32. }
  33. }

ProductService.java

  1. @Service
  2. public class ProductService {
  3. @Autowired
  4. private ProductRepository productRepository;
  5. public Product saveProduct(Product product){
  6. return productRepository.save(product);
  7. }
  8. public List&lt;Product&gt; saveProducts(List&lt;Product&gt; products){
  9. return productRepository.saveAll(products);
  10. }
  11. public List&lt;Product&gt; getProducts(){
  12. return productRepository.findAll();
  13. }
  14. public Product getProductById(int id){
  15. return productRepository.findById(id).orElse(null);
  16. }
  17. public Product getProductsByName(String name){
  18. return productRepository.findByName(name);
  19. }
  20. public String deleteProduct(int id){
  21. productRepository.deleteById(id);
  22. return &quot;product removed !!!&quot;;
  23. }
  24. public Product updateProduct(Product product){
  25. return productRepository.save(product);
  26. }
  27. }

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

  1. {
  2. &quot;timestamp&quot;: &quot;2020-09-24T20:01:15.060+00:00&quot;,
  3. &quot;status&quot;: 500,
  4. &quot;error&quot;: &quot;Internal Server Error&quot;,
  5. &quot;message&quot;: &quot;&quot;,
  6. &quot;path&quot;: &quot;/addProduct&quot;
  7. }

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

  1. 2020-09-25 09:25:50.447 INFO 12128 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 10 ms
  2. 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_
  3. 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
  4. 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.)
  5. at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:210) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  6. at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:148) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  7. at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  8. at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  9. at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  10. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  11. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  12. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  13. at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  14. at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.38.jar:4.0.FR]
  15. at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  16. at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.38.jar:4.0.FR]
  17. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  18. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  19. at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.38.jar:9.0.38]
  20. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  21. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  22. at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  23. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  24. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  25. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  26. at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  27. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  28. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  29. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  30. at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  31. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
  32. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  33. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  34. at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  35. at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  36. at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  37. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  38. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  39. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  40. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  41. at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  42. at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  43. at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  44. at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  45. at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  46. at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
  47. at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
  48. at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
  49. 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

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

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. @Entity
  5. public class Product {
  6. @Id
  7. @GeneratedValue
  8. private int id;
  9. private String name;
  10. private int quantity;
  11. private double price;
  12. // 在下面添加这个
  13. public Product() {
  14. }
  15. }
英文:

Simply create an empty default constructor.

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. @Entity
  5. public class Product {
  6. @Id
  7. @GeneratedValue
  8. private int id;
  9. private String name;
  10. private int quantity;
  11. private double price;
  12. //this one below
  13. public Product()
  14. {
  15. }

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:

确定