About spring integration hibernate using update without exception but no effect (no sql statement output)

When using hibernate alone

openSession()

When not using spring to control transactions, sessionFactory.openSession() is used. In this way, each method will create a new session, and the session must be controlled and closed in the method.

So at the beginning, I used the update method of session directly in the try-with-resource statement, without any transaction, and found that the update method was invalid during unit testing.

There are two workarounds:

  • Plus transaction control: session.beginTransaction()和trans.commit()

  • Add flush method: session.flush()

Session principle: In fact, when we perform session update and delete operations, they will not be executed immediately, but only by executing flush. However, if transaction management is configured, this matter can be handed over to the transaction manager to complete the automatic execution of the flush statement when the transaction is committed.

Using Spring Transaction Management

  1. You need to use getCurrentSession to get the session
  2. Do not show close session during operation
  3. No need for coded transactions, use declarative transactions

 Add the following code to the spring configuration file

At this time, the dao layer only needs to be  session().update(entity)simple

Using Spring transaction annotation management

The transaction problem is identified, but there are no errors in the transaction configuration.

 The reason for the error: there is a problem with the configuration:

web.xml

The problem is: when spring-mvc.xml is loaded by the servlet

If all annotations are registered from the beginning, then when @service is encountered, the transaction configuration is likely to be invalid, especially @Transactional must be invalid. So transaction configuration doesn't work

Solution: Load controllers and other annotations separately. Controller annotations are loaded by springmvc.xml

In the spring configuration file, load other annotations:

This configures it to run and the console also prints the hql statement.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206776&siteId=291194637