2011-03-21 1 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!!! 
}  

теперь у меня есть проблемы, он удаляет ВСЕ ПО, даже если у них есть ссылки на теги.

, но я получаю SQL, который формируется из HQL это как:

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

+0

удалить из A a где [a.bs пуст | a.bs.size = 0 | size (a.bs) = 0] работает для меня. Подробная информация о вашем картографировании? – ssedano

ответ

Смежные вопросы