简体   繁体   中英

Java: Is it possible to know the progress of a transaction.commit operation?

I'm using JPA in my application to bundle a series of insert and updates into one commit() operation.

While that commit is running, is it possible to learn the progress of that operation (0-100%) so I can display that in a progress bar to the user?

I could split my updates into many commits, but that would make the entire job take longer.

I think the only way to create something like that would be to use the org.hibernate.stat.internal.StatisticsImpl class of hibernate . You can programmatically get different metrics from the instantiation of this class. Hibernate statistics generation must be enabled for this to work. You can enable it by setting the property hibernate.generate_statistics to true .

The statistics instance has a method called getQueryExecutionCount() that you might be able to use to build a progress bar. It gives the number of queries that were executed by the current JPA EntityManagerFactory or Hibernate. If you keep calling that method in a while loop while the queries are still running you might be able to show the percentage of completed queries by dividing the return value of getQueryExecutionCount() by the total amount of queries that need to be processed. Heres a good tutorial that explains all the different metrics that are available.

I must also point out that turning on hibernate statistics could slow your application down. So if you want to use this feature in production then you must also test whether this slowdown is acceptable or not.

EDIT: You could also choose to only turn hibernate statistics on right before the queries will run and turn it off after they've completed.

The StatisticsImpl class has a method called setStatisticsEnabled(boolean b) that you can use to programmatically turn it on or off.

EDIT 2: I'm assuming here that you are using Hibernate as the JPA provider. If not i'll remove this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM