MyBatis: how to bypass the local cache and directly get into the database with a certain choice

I am using MyBatis 3.1.
I have two use cases where I need to bypass the local MyBatis cache and directly get into the database.
Since the MyBatis configuration file has only global settings, it is not applicable to my case, because I need it as an exception, and not by default. Attributes MyBatis <select> The XML statement does not include this option.

Use case 1 : 'select sysdate from dual'.
MyBatis caching causes this to always return the same value in a MyBatis session. This causes a problem in my integration test when I try to reproduce the situation with an outdated record.
My workaround was to just use a simple JDBC call.

Use case 2 : 'select' from one stream does not always see the value written by another stream.
Theme 1:

SomeObject stored = dao.insertSomeObject(obj);
runInAnotherThread(stored.getId());
//complete and commit

Theme 2:

//'id' received as an argument provided to 'runInAnotherThread(...)'
SomeObject stored = dao.findById(id);
int count = 0;
while(stored == null && count < 300) {
    ++count;
    Thread.sleep(1000);
    stored = dao.findById(id);
}
if (stored == null) {
    throw new MyException("There is no SomeObject with id="+id);
}

MyException , . . , , MyBatis , 5 , .

, , MyBatis, JDBC?
- MyBatis , () , , .

+4
4

, , , , .

- flushCache="true" select. , .

    <select id="getCurrentDate" resultType="date" flushCache="true">
        SELECT SYSDATE FROM DUAL
    </select>  

- STATEMENT. SESSION (, , ). localCacheScope factory. , , mybatis factory.

+7

.
, flushCache = "true" ' , . "", "select" . , 'select' , , 'select'.

- . Spring, @Transactional ( = Propagation.REQUIRES_NEW). MyBatis Spring, MyBatis .

- MyBatis 'useCache = "false" .

+6

:

 Configuration configuration = MyBatisUtil.getSqlSessionFactory().getConfiguration(); 
            Collection<Cache> caches = configuration.getCaches(); 

           //If you have multiple caches and want a particular to get deleted.           
          // Cache cache = configuration.getCache("PPL"); // namespace of particular XML
            for (Cache cache : caches) { 
                Lock w = cache.getReadWriteLock().writeLock(); 
                w.lock(); 
                try { 
                    cache.clear(); 
                } finally { 
                    w.unlock(); 
                } 
            } 
+1
source

The following annotation may be used Options:

@Options(useCache=false, flushCache=FlushCachePolicy.TRUE)
+1
source

All Articles