Get the App
SLTechnology News&Howtos  ›  Development  › 

How does mybatis use truncate to clear the table

Shulou Source: shulou.com Published: 2022-06-01 06:05:29 09月12日 Update

Editor to share with you how to use mybatis truncate emptying table, I hope you will learn something after reading this article, let's discuss it together!

Use truncate to clear the table Mapper interface void truncateTable (); XML file TRUNCATE TABLE table name

Note: it's a label, not a label.

What happens when using truncate in a transaction method

In the transaction method of a spring project (using the @ transactional annotation):

First execute a delete statement

Then execute a truncate statement

Finally, execute an insert statement

problem

Why did the delete statement and the truncate statement execute successfully, but the insert statement was executed but not committed?

explain

First of all, in the method without transaction annotations, all interactions with the database are handled by mybatis

By default, mybatis is committed automatically by transaction, that is, each sql statement is committed immediately after execution.

After adding transaction annotations, the interaction between the application and the database is handled jointly by spring and mybatis (so they share the same data source):

Spring manages transactions, and mybatis is responsible for the execution of specific sql.

So how are they coordinated?

Spring first creates a connection to start the transaction, and puts the connection into the current thread (threadlocal)

When mybatis executes the sql statement, it gets the connection from the current thread-- which ensures that spring and mybatis are using the same connection

After mybatis executes sql, it checks whether there are transaction comments on the method, and if so, does not execute the commit statement.

Finally, the commit is executed by spring.

This explains the problem in the first place:

After the execution of truncate, the current transaction has been committed (although truncate has better performance than delete, it is a DDL statement and will trigger transaction commit). When sql is executed later, it will not commit because mybatis detects transaction comments

Spring already commits the transaction and will not commit again at the end of the method.

After reading this article, I believe you have a certain understanding of "mybatis how to use truncate clearance Table". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Tags: Transactions statements methods annotations data databases tags articles threads problems processing interpretation success that is at the same time scenarios dead performance interfaces data sources Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL macOS NVidia Shulou Information Docker