简体   繁体   English

实体管理器休眠持久性

[英]Entity manager hibernate persistence

I have 2 entities annotated like below. 我有2个实体,如下所示。 When I try to remove one command line after id from the list of command lines and the application doesn't crashes but it doesn't delete the line. 当我尝试从命令行列表中删除id后面的一个命令行时,应用程序不会崩溃,但不会删除该行。 I'm new to java and hibernate and I have no idea what is the problem. 我是java和hibernate的新手,不知道是什么问题。

@Entity
public class Command {

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

and

@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));

Entity Command is a child of Entity CommandLine so as per the data provided you need to change the Command Entity with: Entity Command是Entity CommandLine的子级,因此根据提供的数据,您需要使用以下Command更改Command Entity:

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

And also you can use the delete method of Entity manager session for removing child object from the session from RAM. 您还可以使用实体管理器会话的delete方法从RAM中的会话中删除子对象。

entityManager.delete(commandLine);

you need to remove the reference to the CommandLine object in Command before removing from database. 您需要从数据库中删除之前在Command删除对CommandLine对象的引用。 eg: 例如:

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

A side note: doing CRUD stuff on entities should be left to Controller and service classes, don't have the objects removing themselves. 附带说明:在实体上进行CRUD操作应留给Controller和service类,不要让对象自行删除。

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

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