-1

Why we open session in hibernate to fetch data from database without persisting it, where as in JPA we use EntityManager to load data but we do not open transaction to just fetch data from database.

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86

1 Answers1

0

Good question. In native Hibernate a session has the same function as an EntityManager in JPA, so why do you most hibernate examples have a transaction when reading data.

If you just opened a session, and only do a read query, you should be fine. However this is NOT recommended. The problem is that if you are using an existing session, your select query could lead to a pre-query-flush, which could end up inserting. You may also want to take a look at this post

Personally I almost never call getTransaction() explicitly on EntityManager or Session. It is much better to use container manager EntityManager/Session and declarative transaction (like Spring @Transactional or J2EEs @TransactionAttribute). You can get an idea how this works by looking at this tutorial. The example is a bit outdated, as you would use spring-data JPARepositories instead of coding your own DAO.

Community
  • 1
  • 1
Klaus Groenbaek
  • 4,820
  • 2
  • 15
  • 30