使用HQL“从空白处删除”子句删除项目

时间:2011-03-21 15:33:04

标签: hibernate jpa playframework hql hql-delete

我在关系中有两个实体

tag <-m:n-> software

我想在删除特定标签后删除所有不是标签链接的软件。我为此编写了HQL查询..

我使用playframework

我覆盖的Tag.delete()

@Override
public Tag delete() {

    Tag t = null;

    // t = super.delete();   // commented for now

    // it should delete ONLY that softwares which are not linked with tags (tags is empty)
    Query q = Tag.em().createQuery("delete from Software s where s.tags is empty ");
    q.executeUpdate();

    return t;
}

我的测试:

@Test
public void testDelete() throws InterruptedException {

    Tag tag1 = new Tag("tag1").save();
    Tag tag2 = new Tag("tag2").save();

    Author author1 = new Author("name", "email").save();

    Software s1 = new Software("soft1", "description1", author1, tag1).save(); // this should be deleted when tag1 is deleting

    Software s2 = new Software("soft2", "description2", author1, tag1, tag2).save(); // this should be deleted, because it links to tag2

    // checks, just in case: 
    Software ss = Software.findById(s1.id);
    assertTrue(ss.isPersistent());
    assertTrue(!ss.tags.isEmpty());
    assertEquals(1, ss.tags.size());

    tag1.delete();

    // try to find the software
    assertEquals(1, Software.findAll().size()); // here it faults, it deletes all!!!
}    

现在我遇到了删除所有软件的问题,即使它们有标签链接。

但我得到的是由HQL组成的SQL,如:

delete from Software where not (exists (select tag.id from Tag_Software ts, Tag tag where Software.id=ts.softwares_id and ts.tags_id=tag.id))

这是一个很好的SQL(我检查过它),但为什么所有这些在我的上下文中都不能用作HQL?

我的测试说:

失败,预期:&lt; 1&gt;但是:&lt; 0&gt;

两个类的代码是:

public class Tag extends Model {

    @Column(nullable = false, unique = true)
    public String title;

    public Tag(String title) {
        this.title = title;
    }

    @ManyToMany
    public List<Software> softwares = new LinkedList<Software>();

...

@Entity
public class Software extends Model {

    public String title;
    public String description;

    @ManyToOne(optional = false)
    public Author author;

    @ManyToMany(mappedBy = "softwares")
    public List<Tag> tags = new LinkedList<Tag>();

...

1 个答案:

答案 0 :(得分:1)

有多种方式:

`softwares.size = 0

尺寸(软件)= 0 `

您可以阅读此内容以了解有关它们的更多信息:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions