Hibernate HQL with interfaces

2019-01-20 13:21发布

According to this section of the Hibernate documentation I should be able to query any java class in HQL

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-polymorphism

Unfortunately when I run this query...

"from Transaction trans where trans.envelopeId=:envelopeId"

I get the message "Transaction is not mapped [from Transaction trans where trans.envelopeId=:envelopeId]".

Transaction is an interface, I have to entity classes that implement it, I want on HQL query to return a Collection of type Transaction.

3条回答
我想做一个坏孩纸
2楼-- · 2019-01-20 13:46

Try importing the interfaces so you don't have to specify the full path. I use a file called imports.hbm.xml to handle all interfaces:

<hibernate-mapping package="com...path.to.implementations">
  <import class="com.path.to.interfaces.Transaction" rename="Transaction"/>
...
</hibernate-mapping>

Then add that to the configuration just like a normal mapping file.

查看更多
小情绪 Triste *
3楼-- · 2019-01-20 13:49

Indeed, according to the Hibernate documentation on Polymorphic queries:

Hibernate queries can name any Java class or interface in the from clause. The query will return instances of all persistent classes that extend that class or implement the interface. The following query would return all persistent objects:

from java.lang.Object o

The interface Named might be implemented by various persistent classes:

from Named n, Named m where n.name = m.name

But because the interface is not mapped (and thus unknown), you need to use the fully qualified name in your HQL query:

from qualified.name.Transaction trans where trans.envelopeId=:envelopeId

This will return instances of all persistent classes that implement your Transaction interface.

查看更多
时光不老,我们不散
4楼-- · 2019-01-20 13:49

I think you need to map the interface as the parent class and the implementing classes as its subclass.

http://docs.jboss.org/hibernate/stable/core/reference/en/html_single/#inheritance-strategies

查看更多
登录 后发表回答