Hibernate Criteria: Is it possible to access a database view with criteria?

耗尽温柔 提交于 2019-12-23 05:13:29

问题


I have a criteria, which I'm trying to join to a database view. I'm wondering if it's possible and if so how to do it?

As I understand, createAlias and createCriteria only join to child objects of the root criteria. I read about detachedCriteria, but it seems that those need to be created on database entities, which the view is not.

The HQL equivalent would be something like this

    select * from root_criteria rc where rc.id in
(select view.id from DATABASE_VW view where view.field is not null)

Thanks in advance


回答1:


You can try XML mapping to create an entity class pointing the database view. Each field in the entity will be mapped to the one selected from the view.

Excerpts from the documentation :

  • There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level, although some DBMS do not support views properly, especially with updates.

  • subselect (optional): maps an immutable and read-only entity to a database subselect. This is useful if you want to have a view instead of a base table.

Below is the sample configuration, modify it accordingly.

 <class name="MappedClassName" mutable="false">
 <subselect>
 select view.id as viewId from DATABASE_VW view    
 </subselect>
 ...
 </class>



回答2:


Yes it is possible to use Views in Criteria.

Create View. Create Java Object(Persistent) which will have mapping member variable for every column you are selecting from view. Create hbm.

You can now use the Java Object in the criteria as you can do it for table.



来源:https://stackoverflow.com/questions/15913238/hibernate-criteria-is-it-possible-to-access-a-database-view-with-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!