A food is a set of operations performed as a logical unit. A logical unit of work must have four properties, namely atomicity, consistency, isolation and durability, or ACID for short.

Atomicity: A transaction is an atomic operation consisting of a series of actions. The atomicity of the transaction ensures that the action either completes completely or does not work at all.

Consistency: Once a transaction has completed (whether successfully or failed), the system must ensure that the business it models is in a consistent state and not partially complete and partially failed. Data in the real world should not be corrupted.

Isolation: There may be many transactions processing the same data at the same time, so each transaction should be isolated from the others to prevent data corruption.

Durability: Once a transaction completes, its results should not be affected no matter what system errors occur so they can recover from any system crashes. Typically, the results of a transaction are written to persistent storage.

The default in JDBC is single statement single transaction Connection conn= Obtain database Connection; conn.setAutoCommit(false); Disable automatic submission. Perform multiple modification operations using Statement. conn.commit(); Submit manually, conn.rollback() if an exception occurs;

Definition of Basic transaction attributes Transaction attributes can be understood as some basic configuration of a transaction, describing how transaction policies are applied to methods. The transaction attribute contains five aspects

public interface TransactionDefinition { int getPropagationBehavior(); // return transaction propagation behavior int getIsolationLevel(); Int getTimeout(); int getTimeout(); Boolean isReadOnly(); // Returns the number of seconds the transaction must complete. // If the transaction is read-only, the transaction manager can optimize based on this return value to ensure that the transaction is read-only}

The first aspect of the transaction is propagation Behavior. When a transaction method is called by another transaction method, you must specify how the transaction should propagate. For example, a method may continue to run in an existing transaction, or it may start a new transaction and run in its own transaction

Propagation behavior meaning PROPAGATION_REQUIRED indicates that the current method must run in a transaction. If the current transaction exists, the method will run in that transaction. Otherwise, a new transaction is started, PROPAGATION_SUPPORTS means that the current method does not need a transaction context, but PROPAGATION_MANDATORY means that the method must run in a transaction, if one exists. If the current transaction does not exist, an exception is thrown, PROPAGATION_REQUIRED_NEW, indicating that the current method must run in its own transaction. A new transaction will be started. If there is a current transaction, it is suspended during the execution of the method. If you use JTATransactionManager, you need to call TransactionManager PROPAGATION_NOT_SUPPORTED to indicate that the method should not run in a transaction. If there is a current transaction, it will be suspended while the method is running. If you use JTATransactionManager, you need to call TransactionManager PROPAGATION_NEVER to say that the current method should not run in a transaction context. If a transaction is currently running, an exception is thrown, PROPAGATION_NESTED indicating that the method will run in a nested transaction if a transaction already exists. Nested transactions can be committed or rolled back independently of the current transaction. If the current transaction does not exist, it behaves as PROPAGATION_REQUIRED. Note that vendor support for this propagation behavior varies. Refer to the resource managers’ documentation to see if they support nested transaction isolation levels the isolation levels define the extent to which a transaction may be affected by other concurrent transactions. 1) Problems caused by concurrent transactions In a typical application, multiple transactions run concurrently, often manipulating the same data to accomplish their respective tasks. Concurrency, while necessary, can cause the following problems.

Dirty reads — Dirty reads occur when one transaction reads data that another transaction has overwritten but not yet committed. If the overwrite is rolled back later, the data obtained by the first transaction is invalid. Nonrepeatable Read — A Nonrepeatable read occurs when a transaction executes the same query twice or more, but gets different data each time. This is usually because another concurrent transaction was updated between the two queries. Phantom Read – Phantom read is similar to unrepeatable reading. It occurs when one transaction (T1) reads several rows of data, followed by another concurrent transaction (T2) inserts some data. On subsequent queries, the first transaction (T1) finds additional records that were not originally present.

Isolation Level Meaning ISOLATION_DEFAULT Default isolation level ISOLATION_READ_UNCOMMITTED The lowest isolation level, allowing uncommitted data changes to be read. May cause dirty reads, illusory reads, or unrepeatable reads ISOLATION_READ_COMMITTED Allows reading of data already committed by concurrent transactions to prevent dirty reads. However, phantom or unrepeatable reads can still occur. The ISOLATION_REPEATABLE_READ results of multiple reads of the same field are consistent, unless the data is modified by the transaction itself to prevent dirty reads and unrepeatable reads. However, phantom reads can still occur. The highest isolation level ISOLATION_SERIALIZABLE, fully subject to ACID, ensures that dirty reads, unrepeatable reads, and phantom reads are prevented, and is also the slowest transaction isolation level, as it is typically achieved by completely locking the database tables associated with the transaction

The third property of a read-only transaction is whether it is read-only. If the transaction only does this to the back-end database, the database can take advantage of the read-only nature of the transaction for some specific optimizations. By making the transaction read-only, you give the database an opportunity to apply any optimizations it sees fit.

Transaction timeout In order for the application to run well, a transaction should not run for too long. Because transactions may involve locking the back-end database, long-running transactions unnecessarily consume database resources. A transaction timeout is a timer for a transaction that automatically rolls back if the transaction is not completed within a certain period of time, rather than waiting for it to complete.

Transaction use in Spring: annotation transactions and programming transactions

Add transaction annotations —- for @Transactional(Propagation) in business methods. If supports = Propagation.REQUIRED, Isolation specifies the isolation level of transactions. The default isolation level of the underlying database is used. If not, code to introduce optimistic lock supplement = Isolation.default, readOnly whether to use read-only transactions, if the query uses read-only, Otherwise, the value is not read-only. = False,timeout To avoid waiting for a long time, set the timeout duration, in s=12.) public void saveUsers() throws Exception 2

<tx:annotation-driven transaction-manager="transactionManager" /> <! Define the implementation of the specific transactionManager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" />Copy the code

3. The default runtime exception rollback undo operation when using Spring’s annotation transaction; Commit the change if it is a non-runtime exception. You can use the rollbackFor= myException.class defined by the attribute in the annotation to define the exception that needs to break the rule rollback. You can use the noRollbackFor= myRuntimeException.class attribute defined in the annotations to define exceptions that need to break the rule without rolling back.

Service interface public interface IUserServ {void createUsers(List users); }

Implementation class @transactional (readOnly = true, propagation = Propagation.SUPPORTS) public class UserServImpl implements IUserServ { @Autowired private UserMapper userMapper;

@Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void createUsers(List<User> users) { if (users ! = null && users.size() > 0) for (User temp : users) userMapper.insertSelective(temp); }Copy the code

}

How Spring annotates transactions: Spring’s transaction module is implemented using AOP, such as transaction property configuration and transaction object abstraction. There is a transactional proxy factory in Spring that uses AOP functionality to generate proxy objects. In this transaction proxy object, the transaction proxy methods are intercepted through a transaction interceptor, using AOP’s interception capabilities. , due to the different database in spring transaction processing, such as the generation of the transaction, commit, rollback, hang, such as spring all did an abstract adapter, and this series of implementation, are from AbstractPlatformTransationInterceptor.

Spring transaction processing consists of the following three main processes: 1. Read and process transaction properties configured in the Spring IoC container, and transform them into internal data structures required by Spring transaction processing. 2. Unified transaction processing process implemented by Spring transaction processing module. This general transaction process includes: handling transaction configuration properties; Transaction configuration properties are tied to threads, etc. 3. Implementation of low-level transaction processing. The realization of the underlying transaction processing in the Spring to the PlatformTransactionManager specific implementation class, such as DataSourceTransactionManager and HibernateTransactionManager.

1, # {}, and{} is a variable placeholder in the Properties file. It can be used for tag attribute values and within SQL. It is a static text substitution, such as ${driver}, which is statically replaced with com.mysql.jdbc.driver. #{} is a parameter placeholder in SQL. Mybatis will replace #{} with? The parameter setting method in PreparedStatement will be used before SQL execution. Number placeholders set parameter values, such as ps.setint (0, parameterValue), #{item.name} takes the value of the name attribute of the item object from the parameter object using reflection, equivalent to param.getitem ().getName().

2, the Xml mapping file, in addition to the common select | insert | updae | delete tags, what other tags? A: There are lots of other tags,,,,,,,, with nine dynamic SQL, trim | where | set | foreach | if | choose | s | otherwise | bind and so on, which for the SQL fragment label, by introducing the SQL TAB, Generates policy labels for primary keys that do not support auto-increment.

In best practice, an Xml mapping file will usually have a Dao interface corresponding to it. How does this Dao interface work? Can methods in the Dao interface be overloaded if their parameters are different? A: Dao interface is also known as Mapper interface. The full name of the interface is the value of namespace in the mapping file, the method name of the interface is the ID value of MappedStatement in the mapping file, and the parameters in the interface method are the parameters passed to SQL. The Mapper interface has no implementation class. When the interface method is called, the interface full name + method name concatenation string is used as the key value to uniquely locate an MappedStatement. For example: Com. Mybatis3. Mappers. StudentDao. FindStudentById, Can only find the namespace for the com. Mybatis3. Mappers. StudentDao id = findStudentById MappedStatement below. In Mybatis, each,, and tag is parsed into an MappedStatement object. Methods in the Dao interface cannot be overridden because of the save and find policy of the full name + method name. The working principle of Dao interface is JDK dynamic proxy. Mybatis will use JDK dynamic proxy to generate proxy objects for Dao interface. Proxy object proxy intercepts interface methods, executes SQL represented by MappedStatement, and returns SQL execution results. 4. How is Mybatis paginated? How does paging plug-ins work? A: Mybatis uses the RowBounds object for paging, which is memory paging performed on the ResultSet ResultSet, rather than physical paging. You can either write physical paging directly in SQL or use paging plug-ins to complete physical paging. The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a custom plug-in to intercept the SQL to be executed in the interception method of the plug-in, and then rewrite the SQL to add the corresponding physical paging statement and physical paging parameters according to the dialect. Select t.* from (select * from student) t limit 0,10 A: Only ParameterHandler, ResultSetHandler, StatementHandler, and Executor interfaces can be used as plugins in Mybatis. The interface method interception function is implemented by generating proxy objects for the interface to be intercepted. Each of the four methods of the interface object is invoked, specifically the Invoke () method of InvocationHandler, which, of course, only intercepts those methods that you specify to be intercepted. Implementation of Mybatis Interceptor interface and autotype intercept () method, and then to the plug-in to write notes, specify which interface to intercept method which can, remember, don’t forget to you write a plug-in that is configured in the configuration file. 6, Mybatis perform batch insert, can return database primary key list? A: Yes, JDBC can, Mybatis certainly can. 7, Mybatis dynamic SQL does what? What is the dynamic SQL? Can you briefly explain how dynamic SQL is executed? A: Mybatis dynamic SQL allows us to write dynamic SQL in the form of tags in Xml mapping files, complete logical judgment and dynamic splicing SQL functions, Mybatis provides nine dynamic SQL tags trim | where | set | foreach | if | choose | s | otherwise | bind. Its implementation principle is to use OGNL to calculate the value of the expression from the SQL parameter object, according to the value of the expression dynamic splicing SQL, to complete the function of dynamic SQL. How does Mybatis encapsulate SQL execution results as target objects and return them? What are the mappings? A: The first is to use tags to define the mapping between column names and object attribute names one by one. The second method is to use SQL column alias function, write column alias AS object attribute NAME, such AS T_NAME AS NAME, object attribute NAME is generally NAME, lowercase, but column NAME is not case sensitive, Mybatis will ignore the case of column NAME, intelligently find the corresponding object attribute NAME. You can even write T_NAME AS NaMe, Mybatis will work just AS well. Mybatis creates objects by reflection after mapping between column names and attribute names. At the same time, Mybatis uses reflection to assign values to the attributes of the object one by one and returns them. The assignment cannot be completed for those attributes that cannot find the mapping relationship. 9, Mybatis can execute one-to-one, one-to-many associated query? What are the implementation methods and the differences between them? A: Yes, Mybatis not only can execute one-to-one, one-to-many associative query, but also can execute many-to-one, many-to-many associative query, many-to-one query, actually is one-to-one query, just need to change selectOne() to selectList(); Many-to-many queries, which are essentially one-to-many queries, simply change selectOne() to selectList(). Associated object query, there are two ways to achieve, one is to send a separate SQL query associated object, assign to the master object, and then return the master object. The other is to use nested query, which means to use JOIN query. One part of the column is the attribute value of object A, and the other part is the attribute value of associated object B. The advantage is that only one SQL query can be sent to find out the main object and its associated object. If a join query contains 100 records, how can we determine whether there are 5 primary objects instead of 100? The principle of its de-duplication is the sub-label within the label, which specifies the ID column that uniquely determines a record. Mybatis can complete the de-duplication function of 100 records according to the column value. There can be more than one, which represents the semantic meaning of joint primary key. Similarly, the associated object of the main object is repeated according to this principle, although in general, only the main object will have repeated records, and the associated object will not repeat. Does Mybatis support lazy loading? If so, how does it work? A: Mybatis only supports lazy loading of association associative objects and collection associative objects. Association refers to one-to-one query and collection refers to one-to-many query. In Mybatis configuration file, you can configure whether to enable lazy-loading lazyLoadingEnabled = true | false. The principle is that CGLIB is used to create a proxy object for the target object. When the target method is called, the interceptor method is entered, such as a.geb ().getName(). The interceptor invoke() method finds that A.geb () is null. A. setb (); a.getName (); a.getname (); a.getb (); a.getname (); This is the basic principle of lazy loading. Of course, not only Mybatis, almost all including Hibernate, support lazy loading principle is the same. 11. In the Xml mapping files of Mybatis, can the IDS of different Xml mapping files be repeated? A: For different Xml mapping files, if namespace is configured, the ID can be repeated. If no namespace is configured, the ID must be unique. After all, namespaces aren’t necessary, just a best practice. Namespace + ID is used as the key of Map<String, MappedStatement>. If there is no namespace, only ids are left. Duplicate ids will overwrite each other. With a namespace, the natural ID can be repeated. With different namespaces, the namespace+ ID will naturally be different. How to perform batch processing in Mybatis? A: Use BatchExecutor for batch processing. What Executor executors does Mybatis have? What’s the difference between them? A: Mybatis has three basic Executor executors: SimpleExecutor, ReuseExecutor, and BatchExecutor. SimpleExecutor: Every time an Update or select is performed, a Statement object is opened and the Statement object is closed immediately. ReuseExecutor: If the Statement object exists, use it. If the Statement object does not exist, create it. After the Statement object is used, place it in Map<String, Statement> for next use. In short, the Statement object is reused. BatchExecutor: Update (no SELECT, JDBC batch does not support SELECT), add all SQL to the batch (addBatch()), and wait for execution (executeBatch()), which caches multiple Statement objects. Each Statement object is addBatch() and waits for the executeBatch() batch to be executed one by one. Same as JDBC batch processing. Scope: These Executor features are strictly limited to the SCOPE of the SqlSession lifecycle. How to specify which Executor to use in Mybatis? A: in the Mybatis configuration file, you can specify the default ExecutorType ExecutorType, or manually pass ExecutorType parameters to the SqlSession creation method of DefaultSqlSessionFactory. Can Mybatis map Enum classes? A: Mybatis can map enumeration classes, not only enumeration classes, Mybatis can map any object to a column of a table. The mapping is done by customizing a TypeHandler that implements the setParameter() and getResult() interface methods of TypeHandler. TypeHandler performs a conversion from javaType to jdbcType and a conversion from jdbcType to javaType as setParameter() and getResult(). Represents setting the SQL question mark placeholder parameter and getting the column query result. 16, Mybatis mapping file, if A tag refers to the content of B tag by include, can B tag be defined after A tag, or must be defined before A tag? A: Although Mybatis parses Xml mapping files in order, the referenced B tag can still be defined anywhere and Mybatis can recognize it correctly. The principle is that Mybatis parses tag A and finds that tag A references tag B, but tag B has not been parsed yet and does not exist. At this point, Mybatis will mark tag A as unparsed and continue to parse the remaining tags, including tag B. After all tags are parsed, Mybatis will re-parse those tags marked as unparsed, and then parse A tag, B tag already exists, A tag can be normally parsed. 17. Describe the mapping relationship between Mybatis Xml mapping file and Mybatis internal data structure. A: Mybatis encapsulates All Xml Configuration information inside the All-in-one heavyweight object Configuration. In an Xml mapping file, the tag is resolved to a ParameterMap object, and each of its child elements is resolved to a ParameterMapping object. The tag is resolved to a ResultMap object, and each of its child elements is resolved to a ResultMapping object. Each,,, and tag is parsed into a MappedStatement object, and the SQL inside the tag is parsed into a BoundSql object.

Why Mybatis is a semi-automatic ORM mapping tool? What’s the difference between it and automatic? A: Hibernate is a fully automated ORM mapping tool. When using Hibernate to query associated objects or associated collection objects, it can be directly retrieved based on the object relational model, so it is fully automated. While Mybatis needs to write SQL manually when querying associated objects or associated collection objects, so it is called semi-automatic ORM mapping tool.