In what cases to work with the database can not do without the Hibernate interface Session .

Is it true that the Session API should be resorted to (in fact, it is impossible not to resort to) in the case when you build queries based on HQL | JPQL HQL | JPQL , or Criteria API ? And this is probably the only reason.

It seems that in 90% of cases they do.

But the EntityManager API contains the createQuery , createNativeQuery , createNamedQuery methods themselves - why not use the methods of this interface?

And what is the difference between Session in JPA and Hibernate ?

    1 answer 1

    There are so-called. Container Managed Transactions (CMT) , i.e., container-managed transactions.

    A container is an environment in which your application runs, for example, an application server. When using CMT your software does not control the start / end of transactions; instead, the container decides when to start transactions and when to complete them.

    Thus, in the source code you do not have transaction.begin()/transaction.commit(). lines transaction.begin()/transaction.commit().

    When working with CMT , EntityManager is usually used . Normally, the EntityManager passed to your application by the container using Dependency Injection (DI) .

    There are Bean Managed Transactions (BMT) . They represent the same thing as CMT , but with one difference - you explicitly manage transactions in your code, and you do not trust the container. EntityManager and DI are also used here.

    There is another approach - you do not use DI , instead, your application implements code that independently accesses the data source. In such applications, work is usually done through Session .

    I have described the general case, and quite often there are also special cases from it. For example, you need to access the specific Session functions in an application using the CMT . There are also cases when DI does not work: it usually happens when you need to access a data source from a stream created not by the container, but by your application.

    The features available from Session and from EntityManager are the same at 99%. Deciding what to use is architectural rather than functional.