no currentsessioncontext configured

Error when using Hibernate framework: no currentsessioncontext configured!


  This error is caused when we use getCurrentSession();. The reason is that the currentSession configuration is wrong, which is related to transactions. When we use currentSession, we need to configure the following transaction in hibernate.cfg.xml:


  1. If it is a local transaction:

    <property name="hibernate.current_session_context_class">thread</property>


  2. If it is a global transaction

    <property name="hibernate.current_session_context_class">jta</property>

Just configure it like this!


  Of course, if you use sessionFactory.openSession() instead of sessionFactory.getCurrentSession() to get the session object, this error will not occur.


  Talk about the difference between getCurrentSession() and openSession() methods:


    openSession() is to reopen a Session regardless of the situation, and getCurrentSession(); relatively adds a judgment. It will be called directly if there is a Session, and it will be created if there is no session. If there is a transaction operation, getCurrentSession (); Better, it is easy to make a thread have only one session object.


  Local transactions and jta transactions:


    Local transactions: When using JDBC transaction demarcation, you can combine multiple SQL statements into a single transaction. One disadvantage of JDBC transactions is that the scope of the transaction is limited to a database connection. A JDBC transaction cannot span multiple databases.


    jta transaction: JTA is a high-level, implementation-independent, protocol-independent API that applications and application servers can use to access transactions.
  JTA allows applications to perform distributed transactions - accessing and updating data on two or more network computer resources, which can be distributed across multiple databases. The JTA support of the JDBC driver greatly enhances data access capabilities.


    Difference: The limitation of JDBC transaction control is within a database connection, but its use is simple; JTA transaction is powerful, and the transaction can span multiple databases or multiple DAOs, which is more complicated to use.

Source: https://blog.csdn.net/fightfaith/article/details/51750080

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326594293&siteId=291194637