繁体   English   中英

Java Spring JPA存储库实体未删除

[英]Java spring JPA Repository Entity is not deleted

在我的代码中,我使用扩展JpaRepository ProductRepository接口来获取实体并尝试将其删除:

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {}

代码和代码的System.out.println()输出:

@PostMapping("/admin/product/delete")
public String deleteProduct(
        @RequestParam String productId
){
    Long id = Long.parseLong(productId);
    System.out.println("long id from deleteProduct: " + id);

    productService.deleteProductById(id);
    return "redirect:/product";
}

sysout:

 long id from deleteProduct: 38

服务方法deleteProductById()

public void deleteProductById(long productId){
    Product product = productRepository.getOne(productId);
    System.out.println("Product:\n" + product);
    productRepository.delete(product);}

sysout from deleteProductById

Product:  Product{id=38, productName='zip',
producer=lightmarket.mvc.model.domain.Producer@182a383}

但是实体没有被删除...我必须指出,所有其他CRUD操作都可以工作。 创建,更新,阅读-一切正常! 只有“删除”无效。

您的Product类的equals和hashcode可能存在问题,并且您从数据库加载的对象与您要删除的对象不同。

通过id删除产品的更好方法是使用id而不是product对象。

您可以更换

productRepository.delete(product);

productRepository.delete(productId);

其中productId的类型为Long。 这也将避免附加查询。

JpaRepository扩展了CrudRepository ,因此您可以使用:

对于您的通用类型, Crudrepository.deleteById()会花费很长的时间(请参阅参考资料)。

在此处输入图片说明

因此,在您的服务中,您将遇到以下情况:

@Service
public class ProductService {

    @Autowired
    ProductRepository repo;

    public void deleteProductById(Long id) {

        System.out.println("Deleting product with id: " + id);

        // USE deleteById(Long id) and directly pass the id
        // Defined in CrudRepository
        repo.deleteById(id);

        // DON'T use delete() and pass a product
        //repo.delete(product);

    }
}

然后,您的控制器像通常一样从该服务调用service.deleteProductById()

参见文档: https : //docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html?is-external=true#deleteById-ID-

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM