Entfernen Sie Elemente mithilfe der HQL -Klausel "Löschen von woher leer"
-
28-10-2019 - |
Frage
Ich habe zwei Einheiten in einer Beziehung
tag <-m:n-> software
Und ich möchte alle Software löschen, die nach dem Löschen eines bestimmten Tags keine Links mehr zu Tags sind. Ich schreibe die HQL -Abfrage dafür ..
Ich benutze Playframework
Mein überschriebenes 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;
}
mein Test:
@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!!!
}
Jetzt habe ich das Problem, dass es alle Software löscht, auch wenn sie Links zum Tag haben.
Aber ich bekomme SQL, das aus HQL gebildet wird. Es ist wie:
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))
Und es ist gut SQL (ich habe es überprüft), aber warum alles nicht als HQL in meinem Kontext funktioniert ...?
Mein Test sagt:
Versagen, erwartet: <1> Aber war: <0>
Der Code für zwei Klassen ist:
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>();
...
Lösung
Es gibt vielfältige Möglichkeiten:
`Software.size = 0
Größe (Software) = 0 `
Sie können dies lesen, um mehr über sie zu erfahren:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions