Spring Hibernate-CrudRepository和SessionFactory之间的区别 [英] Spring Hibernate - difference between CrudRepository and SessionFactory

查看:109
本文介绍了Spring Hibernate-CrudRepository和SessionFactory之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用Hibernate来保存我的模型.我似乎找到了两种方法来做到这一点.

I am looking into persisting my model using Hibernate. I seem to find two approaches to do this.

第一个正在使用SessionFactory,例如:

The first one is using SessionFactory, for example:

public Collection loadProductsByCategory(String category) {
        return this.sessionFactory.getCurrentSession()
                .createQuery("from test.Product product where product.category=?")
                .setParameter(0, category)
                .list();
    }

另一个使用扩展了CrudRepository的带注释子类/接口:

The other one uses an annotated subclass/interface extending CrudRepository:

@Transactional
public interface UserDao extends CrudRepository<User, Long> {
  public User findByEmail(String email);
}

有时也看到@Repository注释,而不是@Transactional.有什么区别?

Also instead of @Transactional sometimes I see a @Repository annotation. What is the difference there?

我没有找到何时/应该使用前一种或后一种方法"的答案,所以我可以得到一个解释吗?

I have not found an answer to "when would/should I use the former or latter approach", so could I get an explanation?

推荐答案

实际上,您可以在Spring docs网站上找到这些注释的描述.

Merely you can find description for these annotations on the Spring docs site.

很快,要回答您的问题,它们之间的区别是它们用于不同的目的.

Shortly, to answer your questions the difference between them is they are used for different purposes.

  • @Transactional is used to demarcate code involved into transaction. It's placed on classes and methods.

用于定义支持事务的Spring bean,也可以在DI中使用.

@Repository is used to define a Spring bean that support transactions, it can be used in DI as well.

它们可以在同一个类中同时使用.

They can be used both on the same class.

这篇关于Spring Hibernate-CrudRepository和SessionFactory之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆