MySQL+Hibernate删除表行报错:delete(id)无法适配TableColumn类型
解决JavaFX删除按钮调用Hibernate delete方法时的类型不匹配错误
看起来你遇到的问题是类型不匹配导致的编译器报错:你的delete(Integer id)方法需要接收整数类型的id,但你传递过去的是TableColumn对象,这就难怪编译器会提示“cannot be applied to (javafx.scene.control.TableColumn)”了。
问题出在你没有正确获取选中行对应的实体id,而是误传了TableColumn类型的变量。下面是修正后的完整步骤和代码:
修正步骤
- 获取选中的实体对象:从TableView的选中模型中直接获取选中的
ProductEntity对象,而不是只拿索引。 - 提取实体的id:从选中的实体中取出对应的id值,再传给delete方法。
- 增加空值校验(可选但推荐):避免因为选中状态异常导致的空指针问题。
修正后的代码
button_del.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseEvent -> { // 获取选中的实体对象,而不是索引 ProductEntity selectedProduct = tableView_tableAll.getSelectionModel().getSelectedItem(); if (selectedProduct != null) { // 从实体中取出id,传给delete方法 delete(selectedProduct.getId()); // 同时可以从TableView中移除该行,更新界面显示 tableView_tableAll.getItems().remove(selectedProduct); } else { // 未选中任何行时的提示 Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Ошибка"); alert.setHeaderText("No row selected for deletion"); alert.setContentText("Select row in table"); alert.showAndWait(); } }); private void delete(Integer id ) { Session session = utils.HibernateSessionFactory.getSessionFactory().openSession(); session.beginTransaction(); ProductEntity productEntity =(ProductEntity) session.get(ProductEntity.class,id); if (productEntity != null) { // 增加判断,避免id不存在导致的异常 session.delete(productEntity); } session.getTransaction().commit(); session.close(); }
关键说明
- 原来的
tableView_tableAll.getSelectionModel().getSelectedIndex()只能拿到行的索引,但你需要的是该行对应的实体对象,所以改用getSelectedItem()更直接。 - 确保你的
ProductEntity类中有getId()方法,并且该方法返回的是Integer类型(和delete方法的参数类型一致)。 - 在delete方法中增加了对
productEntity的空值判断,防止传入无效id时出现空指针异常。
内容的提问来源于stack exchange,提问作者Елена Чччччччч
相关产品推荐
相关产品推荐

