我正在研究使用 Hibernate 来持久化我的模型。我似乎找到了两种方法来做到这一点。
第一种是使用SessionFactory
,例如:
public Collection loadProductsByCategory(String category) {
return this.sessionFactory.getCurrentSession()
.createQuery("from test.Product product where product.category=?")
.setParameter(0, category)
.list();
}
另一个使用扩展 CrudRepository
的注释子类/接口(interface):
@Transactional
public interface UserDao extends CrudRepository<User, Long> {
public User findByEmail(String email);
}
此外,有时我会看到 @Repository
注释,而不是 @Transactional
。有什么区别?
我还没有找到“我什么时候/应该使用前一种或后一种方法”的答案,所以我能得到解释吗?
最佳答案
您只能在 Spring 文档站点上找到这些注释的描述。
简而言之,为了回答您的问题,它们之间的区别在于它们用于不同的目的。
@Transactional
用于划定事务涉及的代码。它位于类和方法上。@Repository
用于定义一个支持事务的Spring bean,它也可以在DI中使用。
它们可以在同一个类中使用。
关于java - Spring Hibernate - CrudRepository 和 SessionFactory 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36234206/