Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 908
Martin Melka Avatar asked Oct 15 '25 15:10

Martin Melka


1 Answers

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.

like image 104
Roman C Avatar answered Oct 17 '25 03:10

Roman C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!