2011-03-21 56 views
1

「從哪裏是空刪除」我有一個關係使用HQL移除項條款

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工作我的背景......?

我的測試說:

故障,預計:< 1>卻被:< 0>

兩個類的代碼是:

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

見http://stackoverflow.com/questions/5368522/why-this-hibernate-template-bulkupdate-doesnt-work/5369277# 5369277 – axtavt 2011-03-21 16:22:31

+0

從A a中刪除[a.bs爲空| a.bs.size = 0 |大小(a.bs)= 0]適用於我。你的映射的細節? – ssedano 2011-03-21 16:40:31

回答