Spring Transactions 与 Hibernate 和 SQL 最佳实践
我们目前正在使用 Spring MVC 来实现 REST Web 服务。我们现在想要实现某种数据持久性,我正在研究有哪些选项。 Spring Transactions + Hibernate + MySQL 似乎是一种非常流行的方法,但我看过的每个博客/教程的做法都不同。
谁能指导我什么可以被认为是使用 Spring 进行数据持久化的“最佳实践”?我想让它基于注释,因为这对我来说似乎更自然且易于维护。
但现在在某些地方我读到不应再使用 HibernateTemplate
。有些人使用 *Dao 接口和 *DaoImpl 配合 @Repository
方式,而另一些人则使用 *Service 配合 @Service
方式。
预先感谢您的任何建议。
We are currently using Spring MVC to implement REST web services. We now want to implement some kind of data persistence, and I am looking at what the options are. Spring Transactions + Hibernate + MySQL seem to be a quite popular approach, but every single blog / tutorial I have looked at does it differently.
Can anyone guide me to what could be considered the "best practice" for data persistance using Spring? I would like to make it annotation based, as this seems more natural and maintainable to me.
But now in some places I have read that HibernateTemplate
should not be used anymore. And some people use the *Dao interface and *DaoImpl with @Repository
approach, while others use *Service with @Service
approach.
Thanks in advance for any advice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HibernateTemplate 确实不是很有用,Spring 文档建议考虑不再使用它。
@Repository 和 @Service 基本上做同样的事情,除了(AFAIK)两件事:
HibernateTemplate is indeed not very useful, and the Spring doc advises considering not to use it anymore.
@Repository and @Service basically do the same thing, except (AFAIK) two things:
当 Hibernate 不支持每个线程一个会话的概念时,就需要 Hibernate 模板。现在更好的方法是直接使用 SessionFactory 上的 getCurrentSession 方法。
对于 HibernateTemplate 来说,另一个问题是,如果 SessionFactory 上公开了更新的 api,那么就必须等待 Hibernate Template 的新版本来支持它。
简而言之,直接使用SessionFactory
Hibernate Template was needed when hibernate did not supported the notion of having one session per thread. Now the better approach is to use getCurrentSession method on SessionFactory directly.
With HibernateTemplate the other issue is that if there are newer api's exposed on SessionFactory then one has to wait for the new release of Hibernate Template to support that.
In a nutshell, use SessionFactory directly
HibernateTemplate 文档中不鼓励使用 HibernateTemplate,网址为
http://static.springsource.org/spring/docs/2.0.3/api/org/springframework/orm/hibernate3/HibernateTemplate.html
@Repository 或 @Service 的使用没有任何区别,但我相信这些注释将来会有进一步的 DAO/Service 级别支持,这将使他们的用法更加精确。
我个人更喜欢在 DAO 层中使用 @Repository 来划分我的服务层和业务层。
The usage of HibernateTemplate is discouraged in the HibernateTemplate documentation at
http://static.springsource.org/spring/docs/2.0.3/api/org/springframework/orm/hibernate3/HibernateTemplate.html
The usage of @Repository or @Service does not make any difference but I believe that these annotations would have further DAO/Service level support in the future which would make their usage more precise.
I personally prefer the usage if @Repository in the DAO layer to demarcate my service and business layers.