Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set FlushMode to COMMIT in SPRING DATA for a single method

I would like to make a single method to run without the FlushMode.ALWAYS.

So I need to setFlushMode(FlushMode.COMMIT) but I don't know how to do that and I'm starting to think that it's not possible using spring data.

I tried to autowire SessionFactory and do this

sessionFactory.getCurrentSession().setFlushMode(FlushMode.COMMIT);

But I got this error

No qualifying bean of type [org.hibernate.SessionFactory] found for dependency...

What I understand is that I can't autowire session factory, so I can't use that way of setting flush mode.

Then my question is

Is there a way to set flush mode for a single method using spring data? How?

like image 517
Ramon Marques Avatar asked Jun 20 '17 13:06

Ramon Marques


People also ask

How do I set JPA to flush mode?

If you want to use the FlushModeTypes AUTO or COMMIT, which are defined by the JPA specification, you can call the setFlushMode method on your Query or TypedQuery interface. Query q = em. createQuery( "SELECT p from ChessPlayer p" ); q.

Does JPA flush commit?

JPA also defines a COMMIT flush mode, which is described as follows: If FlushModeType. COMMIT is set, the effect of updates made to entities in the persistence context upon queries is unspecified. When executing a JPQL query, the persistence context is only flushed when the current running transaction is committed.

How do I commit a transaction in spring boot?

Commit a transaction by calling the commit() method on the Connection interface. This tells your database to perform all required consistency checks and persist the changes permanently. Rollback all operations performed during the transaction by calling the rollback() method on the Connection interface.

What is difference between JpaRepository and CrudRepository?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

I ended annotating my find method in my JPARepository interface like this:

@QueryHints(value = { @QueryHint(name = org.hibernate.annotations.QueryHints.FLUSH_MODE, value = "COMMIT") })
    List<ConcatenaCep> findByCep(Integer cep);
like image 186
Ramon Marques Avatar answered Sep 20 '22 02:09

Ramon Marques