Where and in which use case should I use SessionFactory and Session in Hibernate/ JPA

Viewed 56

I am learning Hibernate and JPA and I know the difference between those. While exploring code from github I checked out some projects . But I didn't find the usage of Session/ SessionFactory (I read about EntityManagerFactory as well). These projects are using JPARepository. What is the purpose of Session/ SessionFactory. Is it already taken care of in JPA/ Hibernate latest version automatically?

Please guide me on this.

1 Answers

Hibernate is an implementation of the JPA specification which predates the interfaces defined by JPA, so it has it's own API that you can interact with. Apart from that, Hibernate also offers a lot more features through it's API that JPA does not specify.

Usually, it's fine to just program against the EntityManager/EntityManagerFactory interfaces and use unwrap() to get access to Session/SessionFactory if you need some Hibernate specific features. This is why you rarely see uses of Session/SessionFactory. A major reason for doing this is to improve portability. I don't think it's reasonable to just switch between JPA providers just as much as it's usually not reasonable to switch between databases. If you want to get the most out of your system, you will at some point use the proprietary features of the projects/products that you use and that is fine. Another good reason to use the JPA APIs is that there is a lot of learning material around as it applies to all JPA compliant implementations. Since JPA has a specification document, you can also read into that if you want to know how something is supposed to work. Although Hibernate has a reference documentation as well, it's probably not as detailed in every aspect as the JPA specification.

Related