DeleteById方法返回null

时间:2019-01-27 15:22:50

标签: spring spring-data-jpa

我尝试使用Spring数据deleteById方法从数据库中删除一行,但是它返回null。

ProductServiceImpl

public void  removeOne(Long id) {
    Product product = findById(id);
    productRepository.deleteById(product);

ProductRepository

public interface ProductRepository extends CrudRepository<Product, Long> {
    void deleteById(Product product);

控制器

@RequestMapping(value="/remove", method=RequestMethod.POST)
public String remove(@ModelAttribute("id") String id, Model model) {
    productService.removeOne(Long.parseLong(id.substring(10)));
    List<Product> productList = productService.findAll();
    model.addAttribute("productList", productList);
    System.out.println("deleted successfully !!!!");
    return "redirect:/product/productList";
}

2 个答案:

答案 0 :(得分:0)

为什么把它写的很复杂。不需要一些代码。首先,扩展CrudRepository,这意味着您不需要创建自定义方法 void deleteById(Product product); ,因为crud包含方法deleteById。 其次,控制器为何使用: @RequestMapping(value =“ / remove”,method = RequestMethod.POST)。我认为必须: @DeleteMapping(“ / remove”)。并且仅在控制器中调用。

@Autowired
private ProductRepository  productRepository;

@DeleteMapping("/remove/{id}")
public String remove(@PathVariable String id) {
    productRepository.deleteById(id);
    return "redirect:/product/productList";
}

答案 1 :(得分:0)

@Autowired
私有ProductRepository productRepository;

@RequestMapping(value =“ / remove”,method = RequestMethod.POST)
public String remove(@RequestParam字符串ID){
    productRepository.deleteById(id);
    返回“重定向:/ product / productList”;
}