Why does fetching from a DB cursor returns always the same result set with MyBatis and Spring Transaction - postgresql

My setup is Postgres database which is connected via JDBC driver to a Tomcat server (which is responsible for connection pooling), which again serves this data source via JNDI to an Spring application.
In the java application I use MyBatis and MyBatis-Spring for querying the database.
Now I want to page through a table using a cursor as shown in this simple example http://www.postgresql.org/docs/9.3/static/sql-fetch.html.
Since a cursor needs to be run within a DB transaction I annotated the relevant method with #transactional annotation provided by the Spring DataSourceTransactionManager (see http://mybatis.github.io/spring/transactions.html)
This is where the crazy part starts. On runtime every FETCH FORWARD 1000 FROM CURSOR queried by MyBatis mapper does return one and the same result set. So it seems the cursor position gets rolled back on every call. So it will return the first 1000 rows of the table avery time.
Why do the following fetches do not return the next chunks of records?

I figured out that MyBatis uses a cache mechanism which isn't quite intelligent in my eyes https://mybatis.github.io/mybatis-3/configuration.html.
In fact MyBatis by default caches all queries executed during a session. Session means transaction or per connection. So on AutoCommit this is no problem. But not for use with a cursor where the fetch statement does not change within a transaction.
So once the first data from the DB has been fetched from the cursor the result was cached in memory and no following fetches were queried to the DB.
The solution is the following line in the mybatis-config.xml
<setting name="localCacheScope" value="STATEMENT"/>
So the local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession.
For me it seems like a bug since the default caching scope makes no sense for DB cursors.

Related

Could I use stored persistence context if DB temporarily shut down?

I have to implement some kind of cache, or temporal storage, that matches the following condition :
This cache stores 4 tables from a specific (maria) DB. len(column) < 50, len(row) < 1000
This cache runs innate when a spring web server turned on. When server turned on, it immediately crawls data from DB, stores them into cache, to minimize direct DB querying.
The spring web server fetches data from cache when received HTTP.get resquest.
The spring web server updates DB column when received HTTP.post, HTTP.delete, HTTP.put, by updating the data in cache, and paste them into tables consequently.
The spring web server must not invoke exception when DB suddenly shuts down, and lose connection. It must handle HTTP requests by cached data, delaying any direct connect logic to DB, and synchronize DB data when DB restores.
I'm not familiar to JPA, but it seems that Spring JPA itself supports the former 4 conditions, by using EntityManager and Persistence context.
However, I cannot find any information that makes this context tolerant. I cannot find any option that makes whole JPA structure Check DB connection alive, and only update after checking returns true.
Since I'm requested to use JPA as far as I could, I want to find out whether using JPA to match the conditions above is possible or not.
Thanks for any Information provided.
Could I use stored persistence context if DB temporarily shut down?
No, not really.
The persistence context gets flushed on every commit, which you don't want, because you want to serve queries from the cache.
Also it doesn't serve the result of any kind of query, it just serves entities.
And most importantly: when a flush event happens and the database is not available you will get an exception.

Update and retrieve records from Postgres

I am a new for Postgres. Currently I hit a situation, I need to retrieve a record from DB/table, then update this record with some changes, then retrieve the updated record again to return to customer, these 3 operations are executed sequentially.
After I run the above 3 steps, sometimes it seems the record has not been updated. But in fact the record has been updated, I suspect when I retrieve the record, Postgres return a cached data rather than fresh data. Actually all DB operations are correct, I guess just Postgres returns cached records.
I am wondering if there is any mechanism to flush my updated data immediately?
Another question is, I am wondering which one is a good practice:
Update a record (actually write to DB), then immediately retrieve the record from DB, both operations are using statement to operate.
Update a record (actually write to DB), then don't retrieve record from DB, because we know updated data, we just use these data to return to customer. However, the record might fail to write DB.
Any ideas for the above?
Some programming languages do db calls asynchronously, meaning that your code is moving on to the next db operation without waiting for the first to finish. So, it could be as simple as using your language's "await" keyword to make sure you are waiting for your db to finish the "update record" before trying to read it again.
If you are writing raw sql or you know it is not an issue with making several db call asynchronously, you could try writing your update and read calls as a single transaction.
See https://www.postgresql.org/docs/14/tutorial-transactions.html if you're unfamiliar with writing transactions.

handle sql exception for large data insert

I have a Spring 2.5 application that takes a large (275K) file and parses it. Each record is then inserted into a Postgres db. There is a unique column (not the primaryKey/#Id) that will kick out the attempted record insert. This results in a DataContraintViolationException, which seems natural enough.
The problem I have is this kills the process. Is there a good way to continue processing the entire file, and just log the exception and move onto the next record for insert? I tried wrapping the respository.save(record) in a try/catch, but it still kills the process with a transaction rollback.
A ConstraintViolationException will be wrapped in a PersistenceException and Hibernate will generally mark the transaction for rollback - even if the exception was registered to not cause a rollback at the spring transaction handling level, e.g. via #Transactional(noRollbackFor = PersistenceException.class).
So there needs to be a different solution. Some ideas:
explicitly look whether a corresponding row is already present (one additional select per item)
try every insert in a dedicated transaction (e.g. annotating a corresponding service method with #Transactional(propagation = Propagation.REQUIRES_NEW) (one additional transaction per item)
handle the constraint violation in a custom DB statement (e.g. ON CONFLICT DO NOTHING / other "upsert" / "merge" behavior the DB offers)
The 1st and the 2nd option should offer some potential for parallelization, since selects / inserts can be issued independently from each other and there is no need to wait for unrelated DB roundtrips.
The 3rd option could be the fastest, as it requires no selects, the least amount of DB roundtrips, and statements could be batched; however it probably also needs the most amount of custom setup: Spring JPA bulk upserts is slow (1,000 entities took 20 seconds) (Reporting back which number or even which entities were actually inserted would likely even increase the complexity: How can I get the INSERTED and UPDATED rows for an UPSERT operation in postgres)

Is JPA's flush and JDBC Batch works as same internally?

As per my understanding flush() method of JPA's entitymanager will sync the data available in persistence context with Database in a single DB network call. Thus it avoids multiple DB calls when somebody trying to persist large amount of records. Why can't I consider this as a batch equivalent (I know flush() may not be implemented for that purpose) of JDBC batch insert ? Because, JDBC batch insert also work with the same idea that it make only single DB call for all the statements it added to the statement object ?
From a performance point of view, both are comparable ? Are they work with the same technique ? Internally, at Database side both will generate same number of queries ?
Somebody please make me understand the difference.
entitymanager will sync the data available in persistence context with Database in a single DB network call
No, not at all. That isn't possible. A flush could possibly delete from several tables, insert in several tables, and update several tables. That can't be done in a single network call.
A flush can use batch statements to execute multiple similar inserts or updates though.

Rolling back the transaction when API call was already executed

Recently I've encountered with some problem working with microservices. My main application works with relational databases, the microservice works with Mongo DB and provides ReST API with CRUD methods for some model. CRUD methods are also implemented in the application. A call from the front-end goes to the application first, a new record is created in the relational db (only some of the fields are saved there), then the model is saved externally - in Mongo DB. In the end the transaction is committed. So if something goes wrong and the transaction is rolled back, the API call would already be executed. In the case of creation I can just delete the newly created record from Mongo DB, but in case of Edit I have no idea what to do.
One of the ideas was to overwrite the model in the Mongo DB with the record from the relational database, but in this case the data would be incosistent, as not all the fields are saved there.
Any ideas about this?
There are multiple ways of doing this:
Using a 2PC (2 phase commit): you basically request an operation in any distributed service and then confirm/rollback it afterwards.
Using sagas: With sagas, you are meant to provide some sort of "rollback operation" for operations you did in your distributed services. When you need to roll back an operation that has already been perform you call the service and indicate a rollback.
More information about sagas here: https://microservices.io/patterns/data/saga.html