在 Hibernate 中实现基于条件的搜索页面的优雅方法
使用 Hibernate 如何设计和实现搜索条件页面(具有多个可编辑/可选择字段/下拉列表作为搜索条件),以便查询不会使数据访问器代码混乱。我的意思是没有基于条件的查询字符串串联,最终所有查询都应该放在单独的 xml 文件中。我已经使用 IBatis 的动态查询完成了这样的实现。在 Hibernate 中找不到这样的东西,所以我开始思考在 Hibernate 中实现基于动态标准的页面的优雅方法是什么。
Using Hibernate how would you design and implement a search criteria page (which has multiple editable/selectable fields/drop-downs as search criteria) such that queries shouldn't clutter data accessor code. I mean no query-string concatenation based on conditionals and ultimately all the queries should go in a separate xml file. I've done such an implementation using IBatis's dynamic queries. Couldn't find such thing in Hibernate so I started thinking what would be the elegant way to implement dynamic criteria based page in hibernate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
毫不奇怪,听起来您正在寻找
Criteria
API:Sounds like you are looking for, unsurprisingly, the
Criteria
API:http://docs.jboss.org/hibernate/core/3.5/reference/en/html/querycriteria.html
因为我有同样的问题,我开发了一个通用 Dao 类,它允许动态(使用反射)根据分配给对象的值创建条件并查询数据库,
例如
国家/地区 = new Country();
// 这些值可以说是根据用户帖子分配给您的 servlet
Country.setName("卢森堡");
如果您愿意,请查看 http://sourceforge.net/apps/wordpress/jprovocateur/2010/09/23/simple-example-hibernate-query-the-database-without-hql-or-criteria/< /a> 您可以在其中找到更多详细信息和示例项目。
由于它是一个通用类,因此您可以将它用于所有 Pojo
as I had the same issue, I developed a Generic Dao class that allows dynamically(using reflection) to create the criteria based on the values assigned to the object and query the database
e.g
Country country = new Country();
// these values lets say they were assigned on your servlet based on the user post
country.setName("Luxembourg");
If you like have a look on http://sourceforge.net/apps/wordpress/jprovocateur/2010/09/23/simple-example-hibernate-query-the-database-without-hql-or-criteria/ where you can find more details and the example project.
And as it is a generic class you can use it for all your Pojos
我赞同 Affe 的建议,即 Criteria API正是您正在寻找的内容,并且在处理动态查询时推荐使用。我在下面引用的 Hibernate Querying 102 : Criteria API 很好地说明了这一点:
文章中显示的代码不言自明,只需看看即可。
相关问题
资源
I second Affe's suggestion, the Criteria API is exactly what you're looking for and is recommended when dealing with dynamic queries. This is very nicely illustrated in Hibernate Querying 102 : Criteria API that I'm quoting below:
The code shown in the article speaks for itself, just have a look.
Related questions
Resources