实体经理hibernate持久化

问题描述 投票:0回答:3

我有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();
            }
        }
    }
}
java hibernate
3个回答
0
投票

像这样修改你的entityManager.remove(entityManager.merge(commandLine)线:

entityManager.remove(entityManager.contains(commandLine) ? commandLine : entityManager.merge(commandLine));

0
投票

实体Command是实体CommandLine的孩子,因此根据提供的数据,您需要更改Command实体:

@OneToMany(mappedBy = "command", orphanRemoval=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CommandLine> commandLines;

此外,您还可以使用实体管理器会话的删除方法从RAM中删除会话中的子对象。

entityManager.delete(commandLine);

0
投票

在从数据库中删除之前,您需要删除CommandLine中对Command对象的引用。例如:

...
Command command = commandLine.getCommand();
command.getCommandLines().remove(commandLine);
entityManager.remove(entityManager.merge(commandLine));
...

旁注:在实体上做CRUD的东西应该留给Controller和服务类,不要让对象自行删除。

© www.soinside.com 2019 - 2024. All rights reserved.