Hibernate Read-Only Transaction

后端 未结 1 706
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 01:45

The Hibernate docs show this example:

session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery( \"from Event\" )         


        
1条回答
  •  再見小時候
    2021-01-05 02:12

    SELECT also requires transaction. It is impossible to execute SELECT without any transaction. The fact that you do not have to explicitly start and end a transaction when selecting data from DB using some SQL GUI tools is that these tools are using autocommit mode . In autocommit mode ,database will automatically start and commit the transaction for each single SQL statement such that you don't have to explicitly declare the transaction boundary.

    If you do not end (i.e commit or rollback) a transaction , the database connection used by this transaction will not be released and your database will run out of the available connections eventually.

    For hibernate ,it uses non-autocommit mode by default (which is specified by the property hibernate.connection.autocommit) . So we must declare the transaction boundary and make sure the transaction ends.

    But if you only query data using hibernate API , it is okay even you do not explicitly declare the transaction boundary because of the followings:

    1. Database will typically start a new transaction automatically when the current SQL statement requires one and no transaction is explicitly started before.

    2. Session.close() will close() the underlying Connection .According to the JDBC specification , if java.sql.Connection#close() is called and there is an active transaction , the result of this active transaction depends on the JDBC vendor 's implementation. Usually , JDBC driver will automatically commit or rollback this transaction . But in this case, it doesn't matter whether the transaction commits or rollbacks because you have already get the data you want.

    0 讨论(0)
提交回复
热议问题