Spring Hibernate - difference between CrudRepository and SessionFactory

Viewed 1389

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?

1 Answers
Related