本文介绍了是否可以从与HQL的许多关联中批量删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果是这样,语法是什么?



假设我希望Foo的一个实例与Bar的所有实例无关联:
在SQL它只是:

 从FOO_BAR_MAPPING中删除
其中FOO_ID =?

在HQL中,我认为它会是这样的:

 从Bar.foos删除foos 
其中foos.id =:id

(其中foos是Foo的映射集合)



但似乎是错误的,给出:

  org.hibernate.hql.ast.QuerySyntaxException:Bar.foos未映射

这对于HQL来说甚至是可能的吗?

解决方案

为了回答您的具体问题,不,据我所知,这是不可能的HQL。



我认为你在这里混合SQL和HQL。在SQL中,你确实删除了记录,当然hibernate最终也会这样做。然而,Hibernate / HQL是以面向对象的思维模式设计的,所以在这种情况下的删除意味着你正在删除对象而不是关联。通常你会做如下的事情:

  Foo f = session.get(Foo.class,id); 
f.getBars()。clear();
session.merge(f);

这将通过您指定的标识符来检索对象,并通过清除其集合来删除所有条形关联。很明显,你必须将Foo-Bars关联映射到正确的方向才能发挥作用。


And if so, what is the syntax?

Assume that I want an instance of Foo to be unassociated from all instances of Bar:In SQL it would simply be:

delete from FOO_BAR_MAPPING
where FOO_ID = ?

In HQL, I assumed it would be something like:

delete from Bar.foos foos
where foos.id = :id

(where foos is a mapped collection of Foo)

But appears to be wrong, giving:

org.hibernate.hql.ast.QuerySyntaxException: Bar.foos is not mapped

Is this even possible with HQL?

解决方案

To answer your specific question, no, as far as I'm aware it's not possible with HQL.

I think you're mixing SQL and HQL a little bit here. In SQL, you indeed "delete" records, and of course hibernate will ultimately do that as well. However Hibernate/HQL is designed from an object-oriented mindset, so "delete" in this context means you are deleting objects, not associations. Typically you'd do something like follows:

Foo f = session.get(Foo.class, id);
f.getBars().clear();
session.merge(f);

This retrieves the object by the id you specified, and removes all Bar associations by clearing it's collection. Obviously you have to have the Foo-Bars association mapped in the proper direction for this to work.

这篇关于是否可以从与HQL的许多关联中批量删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:17