我使用Spring将数据存储在数据库中(当我开始正确地将数据写入数据库时)
我将JSON POST发送到我的Spring服务器请求,如下所示:
{
"productName": "name",
"restaurantId": 2,
"categoryId": 3,
"description": "des",
"price": 33.23
}
和接收功能
@RestController
public class NewProductController{
@RequestMapping(value = "/addNewProduct", method = RequestMethod.POST)
public ResponseEntity<NewProduct> update(@RequestBody NewProduct newProduct){
productName = newProduct.getProductName();
categoryId = newProduct.getCategoryId();
restaurantId = newProduct.getRestaurantId();
description = newProduct.getDescription();
price = newProduct.getPrice();
System.out.println(productName);
System.out.println(categoryId);
System.out.println(restaurantId);
System.out.println(description);
System.out.println(price);
NewProductService newProductService = new NewProductService();
newProductService.setData();
return new ResponseEntity<NewProduct>(newProduct, HttpStatus.OK);
}
来自println的数据显示正确。
并从NewProductService
设置setData函数public class NewProductService {
@Autowired
CategoryRepository categoryRepository;
private String productName;
private Long categoryId;
private Long restaurantId;
private String description;
private Double price;
//[...]
@Transactional
public void setData(){
Category customer = categoryRepository.findOne(1L);
System.out.println("Customer found with findOne(1L):");
System.out.println("--------------------------------");
System.out.println(customer);
System.out.println();
}
在Category customer = categoryRepository.findOne(1L);
我收到错误:
2015-08-18 23:12:27.716 ERROR 8092 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at com.drinkandfood.server.Services.NewProductService.setData(NewProductService.java:46)
当我将此代码放入
时@Override
public void run(String... strings) throws Exception {
Category customer = categoryRepository.findOne(1L);
System.out.println("Customer found with findOne(1L):");
System.out.println("--------------------------------");
System.out.println(customer);
System.out.println();
}
我没有收到错误,但预期的答案。 问题出在哪儿?