简体   繁体   中英

Spring Hibernate - difference between CrudRepository and SessionFactory

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

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();
    }

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

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

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?

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.

  • @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM