Hibernate无法从实体列表中删除项目

时间:2016-12-20 14:34:47

标签: java hibernate jpa

我有一个包含List<Application> applications的实体,该实体持久存储在数据库中。我想从数据库中删除一个特定的Application对象,包括它的所有引用,即映射表(JoinTable)中带有Application外键的条目。

虽然我可以从JoinTable映射表中成功删除数据库行,但我无法EntityManager删除实际的Application行 - 该行仍保留在数据库甚至在调用entityManager.remove()之后,或者数据库中的所有表都被擦除干净,或者发生异常。

实体是(为清晰起见,省略了详细信息):

@Entity
@Table(name = "virtual_machine")
public class VirtualMachine extends ExternalObject
{
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "virtual_machine_has_applications", inverseJoinColumns = { @JoinColumn(name = "application_id", nullable = false, updatable = false) })
    private List<Application> applications = new ArrayList<Application>(0);
}

@Entity
@Table(name = "application")
public class Application extends Common
{
    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private VirtualMachine vm;
}

@Entity
@Table(name = "myapp")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyApp extends Application
{
    @Column(name = "myapp_name")
    private String name;
}

现在,我想删除MyApp表格中的特定application,以及virtual_machine_has_applications 中的映射行。这一切都发生在交易中。首先,我搜索要删除的应用程序:

int index = -1;
for (int i = 0; i < virtualMachine.getApplications().size(); i++)
{
    // Find Application to be deleted. virtualMachine is retrieved from within the same scope/transaction.
    Application app = virtualMachine.getApplications().get(i);                  
    if (app instanceof MyApp && someCriterion)
    {
        index = i;
        break;
    }
}

// Attempt to delete the application from the DB:
virtualMachine.getApplications().remove(index);
entityManager.merge(virtualMachine);

这只会删除virtual_machine_has_applications中的行,但该记录仍会保留在application表中。我怎样才能正确删除后者的记录?

这是我尝试过的,没有成功:

Application app = virtualMachine.getApplications().remove(index);
entityManager.merge(virtualMachine);
entityManager.remove(app);

MyApp myApp = null;
for (int i = 0; i < virtualMachine.getApplications().size(); i++)
{
    ...         
    if (app instanceof MyApp && someCriterion)
    {
        index = i;
        myApp = (MyApp) app;
        break;
    }
}

virtualMachine.getApplications().remove(index);
entityManager.merge(virtualMachine);
entityManager.remove(myApp);

这两次尝试都会导致javax.persistence.NoResultException: No entity found for query异常,之后会擦除整个数据库。

我做错了什么?

更新:在没有其他行的情况下仅调用entityManager.remove(myApp);而没有异常,但由于某种原因,数据库中的每个表都被完全擦除(application中不再有任何记录)。

1 个答案:

答案 0 :(得分:0)

解决方案是:

Application app = virtualMachine.getApplications().remove(index);                      
entityManager.merge(virtualMachine);
entityManager.flush();
entityManager.createQuery("delete from Application where uuid=:id").setParameter("id", app.getId()).executeUpdate();

我不知道为什么使用entityManager.remove()无效。