HQLを使用してアイテムを削除します「空の場所から削除」句
-
28-10-2019 - |
質問
私は関係の中に2つのエンティティを持っています
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>
2つのクラスのコードは次のとおりです。
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>();
...
解決
複数の方法があります:
`softwares.size = 0
サイズ(ソフトウェア)= 0 `
あなたはそれらについてもっと学ぶためにこれを読むことができます:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions
所属していません StackOverflow