通用 DAO 和包装器
为了完成一个 uni 项目,我需要创建一个通用的 DAO。
我遵循 Manning 的《Java persistence with hibernate》一书中的通用 DAO 设计。最终采用以下方法。
findById(ID id, boolean lock)
findAll()
findByExample(T example)
makePersistent(T entity)
makeTransient(T entity)
flush()
clear()
问题是这些方法对于我的项目来说还不够,我的项目包括搜索实体、排序和分页。我知道我可以通过创建类似的方法来做到这一点。
List<T> find(DetachedCriteria dc)
问题是,这意味着我向业务层公开了一个休眠接口,但我不希望这样做。
我想创建一个名为 MyCriteria 的接口和一个名为 MyCriteriaImpl 的类,它的作用与 DetachedCriteria 相同,但允许我通过仅更改实现来更改持久性提供程序。我想这是可能的。
问题是我没有时间写这样的代码。
我想知道的是,是否有一种模式可以让我创建 MyCriteria 接口,并且在 MyCriteriaImpl 中只需调用 hibernate criteria api 的方法。
就像:
MyCriteriaImpl mci = new MyCriteriaImpl();
mci.addRestrictionLike(property, String value);
这意味着调用:
DetachedCriteria dc = new DetachedCriteria();
dc.add(Restrictions.like(property, value)
谢谢
In order to finish a uni project I need to create a generic DAO.
I followed the generic DAO design as found in the Manning's book Java persistence with hibernate. en ended up with the following methods.
findById(ID id, boolean lock)
findAll()
findByExample(T example)
makePersistent(T entity)
makeTransient(T entity)
flush()
clear()
The problem is that these method are not enough for my project, which consist of searching entities, ordering them and paging them. I understand that I can do that by creating a method like
List<T> find(DetachedCriteria dc)
The problem is that would mean that I expose an hibernate interface to the business layer and I don't want that.
I want to create an interface say MyCriteria and a class say MyCriteriaImpl that would do the same as the DetachedCriteria but would let me change the persistence provider by changing just the implementation. I guess it's possible.
The problem is that I don't have time to write such code.
What I want to know is if there is a pattern that would let me create the MyCriteria interface, and in the MyCriteriaImpl just call methods of the hibernate criteria api.
Like :
MyCriteriaImpl mci = new MyCriteriaImpl();
mci.addRestrictionLike(property, String value);
and that would just mean a call to :
DetachedCriteria dc = new DetachedCriteria();
dc.add(Restrictions.like(property, value)
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Hades 在通用 DAO 界面中提供了您所需的一切。如果您可以用它替换您自己种植的东西,或者如果您只是寻找参考,您可以浏览它的代码。它支持分页等。
Hades provides all you require in a generic DAO interface. If you can replace your home grown stuff with that or you can browse through its code if you are just looking for reference. It has support for paging etc.
用这个吧。它具有分页以及 lucene 集成。我为我的一个项目创建了这个。确保每个 DAO 都从中扩展。取出不需要的东西。
Use this one. It has pagination as well as lucene integration. I created this one for one of my projects. Make sure every DAO extends from it. Take out what you do not need.