我有2个实体注释如下。当我尝试从命令行列表中删除id之后的一个命令行,并且应用程序不会崩溃,但它不会删除该行。我是java和hibernate的新手,我不知道是什么问题。
@Entity
public class Command {
@OneToMany(mappedBy = "command", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CommandLine> commandLines;
和
@Entity
public class CommandLine{
@ManyToOne(optional = false)
private Command command;
public void deleteCommandLine(long id) {
List<CommandLine> line = command.commandLines();
for (CommandLine commandLine : line) {
if (commandLine.getId() == id) {
try {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.remove(entityManager.merge(commandLine));
entityManager.getTransaction().commit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
像这样修改你的entityManager.remove(entityManager.merge(commandLine)
线:
entityManager.remove(entityManager.contains(commandLine) ? commandLine : entityManager.merge(commandLine));
实体Command
是实体CommandLine
的孩子,因此根据提供的数据,您需要更改Command
实体:
@OneToMany(mappedBy = "command", orphanRemoval=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CommandLine> commandLines;
此外,您还可以使用实体管理器会话的删除方法从RAM中删除会话中的子对象。
entityManager.delete(commandLine);
在从数据库中删除之前,您需要删除CommandLine
中对Command
对象的引用。例如:
...
Command command = commandLine.getCommand();
command.getCommandLines().remove(commandLine);
entityManager.remove(entityManager.merge(commandLine));
...
旁注:在实体上做CRUD的东西应该留给Controller和服务类,不要让对象自行删除。