
典型的java web应用通常采用多层架构,例如:视图层 (views) -> 控制器层 (controllers) -> 服务层 (services) -> 数据访问层 (dao) -> 数据库 (db)。当需要删除一条记录时,前端通常只传递该记录的唯一标识符(id)。核心问题在于,这个id应该如何向下传递,以及在哪个层级执行删除操作。
我们面临两种主要的策略:
流程:View (ID) -> Controller (ID) -> Service (ID) -> DAO (ID) -> DB (DELETE by ID)
优点:
缺点:
适用场景:
流程:View (ID) -> Controller (ID) -> Service (ID) -> DAO (SELECT by ID) -> Service (Model) -> DAO (DELETE Model) -> DB
优点:
缺点:
适用场景:
综合来看,对于大多数删除操作,直接通过ID删除是更推荐的最佳实践。它在性能和简洁性上具有明显优势。关于“应该在层之间传递模型而不是参数”的观点,这并非绝对。在创建或更新操作中,传递完整的模型是合理的,因为需要修改或持久化其所有属性。但对于仅需通过ID即可完成的查询或删除操作,传递ID参数更为高效和恰当。
示例代码(概念性):
// Controller层
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
// 在控制器层可以进行基本的输入验证
if (id == null || id <= 0) {
return ResponseEntity.badRequest().build();
}
productService.deleteProductById(id);
return ResponseEntity.noContent().build();
}
}
// Service层
@Service
public class ProductService {
@Autowired
private ProductDao productDao;
@Transactional // 确保删除操作在事务中执行
public void deleteProductById(Long id) {
// 在服务层进行业务逻辑和权限校验
// 例如:检查用户是否有权限删除此产品
// if (!userService.hasPermissionToDelete(id, currentUser)) {
// throw new AccessDeniedException("No permission to delete this product.");
// }
// 业务校验(如果需要,可能在此处先查询部分信息,但尽量避免加载整个实体)
// Product product = productDao.findById(id);
// if (product == null) {
// throw new ResourceNotFoundException("Product not found with id: " + id);
// }
// if (product.isPublished()) {
// throw new IllegalStateException("Cannot delete a published product.");
// }
productDao.deleteById(id);
}
}
// DAO层
@Repository
public class ProductDao {
@PersistenceContext
private EntityManager entityManager;
public void deleteById(Long id) {
// 使用JPQL或原生SQL直接通过ID删除
// 这种方式效率最高,只执行一条DELETE语句
int deletedCount = entityManager.createQuery("DELETE FROM Product p WHERE p.id = :id")
.setParameter("id", id)
.executeUpdate();
if (deletedCount == 0) {
// 可以选择抛出异常或记录日志,表示未找到要删除的实体
// throw new ResourceNotFoundException("Product not found with id: " + id);
}
// 如果必须使用session.delete(entity) (不推荐用于简单删除)
// Product product = entityManager.find(Product.class, id); // 执行SELECT
// if (product != null) {
// entityManager.remove(product); // 执行DELETE
// }
}
}综上所述,在Spring MVC和Hibernate应用中,当删除操作仅依赖于记录ID且无需对实体完整状态进行复杂业务校验时,直接通过ID进行删除是最佳实践。它能够有效提升系统性能,简化代码逻辑,并更好地适应大规模应用的需求。
以上就是Spring MVC与Hibernate删除记录的最佳实践:参数传递策略解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号