Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Transaction Management of Spring

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

I. basic knowledge of transactions

Database transactions: complex transactions are executed step by step, either as a whole or as a whole.

Must satisfy: atomicity, consistency, isolation, persistence.

Data concurrency problem: dirty read: a read B's uncommitted change data.

Unrepeatable: a read twice and read the data that B has submitted for the second time. (row-level lock)

Phantom reading (virtual reading): a reads the new data newly submitted by B. (table-level locks need to be added)

The first kind of missing update: when A cancels, the original data is restored and the data submitted by B is overwritten.

The second type of missing update: an overwrites the data that B has already submitted.

Database locking mechanism: generally divided into table lock and row lock, there are shared lock and exclusive lock according to concurrency. The database must impose exclusive locks on changed rows; row shared locks, row exclusive locks, table shared locks, table shared row exclusive locks, table exclusive locks.

Transaction isolation level:

6.JDBC support for transactions

II. ThreadLocal

Concept: ThreadLocal is a container that holds thread localization, assigning a separate copy of the variable to each thread that uses this variable.

Principle: the variable copy of each thread is saved through Map. Key is the thread object and the value is the copy of the thread.

Public class TestNum {/ / ① overrides the initialValue () method of ThreadLocal through an anonymous inner class, specifying the initial value private static ThreadLocal seqNum = new ThreadLocal () {public Integer initialValue () {return 0;}}; / / ② to get the next sequence value public int getNextNum () {seqNum.set (seqNum.get () + 1) Return seqNum.get ();} public static void main (String [] args) {TestNum sn = new TestNum (); / / ③ 3 threads share sn, each generating sequence number TestClient T1 = new TestClient (sn); TestClient T2 = new TestClient (sn); TestClient T3 = new TestClient (sn); t1.start () T2.start (); t3.start ();} private static class TestClient extends Thread {private TestNum sn; public TestClient (TestNum sn) {this.sn = sn;} public void run () {for (int I = 0; I)

< 3; i++) { // ④每个线程打出3个序列值 System.out.println("thread[" + Thread.currentThread().getName() + "] -->

Sn ["+ sn.getNextNum () +"] ");}}

Most Bean in spring can be declared as singleton, so spring encapsulates these non-thread-safe bean with Threadlocal so that stateful bean can work in multithreading as sigleton. Spring implements transaction management through Threadlocal

III. Spring's support for transactions

Spring encapsulates the transaction template class TranscationTemplate.

There are three main interfaces for transaction management: PlatformTransactionManager,TransactionDefinition,TransactionStatus.

TransactionDefinition: used to describe the isolation level, timeout, and other transaction attributes of a transaction

PlatformTransactionManager creates a transaction based on the transaction attributes provided by TransactionDefinition; there are three methods: getTransaction, commit, and rollback

TransactionStatus describes the status of the active transaction

3.spring entrusts transaction management to the underlying persistence implementation framework, providing different PlatformTransactionManager interface implementation classes for different persistence frameworks.

3) reference data source

Hibernate

1) Hibernate configuration

Com.mysql.jdbc.Driver jdbc:mysql://localhost/hibernate_test root cheng 20 1 5000 100 3000 2 true org.hibernate.dialect.MySQL5InnoDBDialect update true true false

The main function of the hibernate.cfg.xml file is to configure a session-factory

In session-factory, we mainly configure some database connection information through property. We know that spring usually uses dataSource to express this kind of database connection. In this way, all those connected to the database in the hibernate.cfg.xml file can be killed, directly using spring's dataSource, while dataSource can also use c3p0, dbcp and so on.

In session-factory, in addition to configuring some database connection information through property, there are also some hibernate configurations, such as dialects, automatic table creation mechanism, formatting sql, etc., which also need to be configured.

There is also the most important configuration of the path where the persistence class is located.

2) sessionFactroy configuration of spring

Com.wechat.entity.po ${hibernate.hbm2ddl.auto} ${hibernate.dialect} ${hibernate.show_sql} ${hibernate.format_sql} false

IV. Declare affairs

1. Aop/tx namespace-based configuration: spring adds a tx namespace to the configuration of Schema and defines transaction attributes in the configuration file.

two。 Configure declarative transactions using annotations

1) configure in xml

2) comment on the business class

@ Service@Transactionalpublic class BbtForum {public ForumDao forumDao; public TopicDao topicDao; public PostDao postDao;...}

3) attributes of @ Transactional

Default attribute:

Transaction propagation behavior: PROPAGATION_REQUIRED

Transaction isolation level: IOSLATION_DEFAULT

Read / write transaction attributes: read / write transaction

Timeout:-1

Rollback setting: rehe runtime exception throws rollback, any checked exception does not cause rollback

4) spring needs to use @ Transactional annotations on specific business classes

5) using annotations at the method will override the comments defined by the class. If the method needs to use special transaction attributes, you can use annotations on the method.

@ Transactional (readOnly = true) public Forum getForum (int forumId) {return forumDao.getForum (forumId);}

V. some points for attention in affairs

1. Use a different transaction manager

@ Transactional ("name") uses a transaction manager named name

two。 The purpose of transaction management is to ensure that the transactional nature of data operations (atomicity, consistency, isolation, persistence) is separated from the transaction, DAO can also carry out data operations.

3. Transmissibility of transactions

PROPAGATION_REQUIERD: create one if there is no transaction currently, and add it if you have one.

PROPAGATION_SUPPORTS: supports the current transaction and is not executed in a non-transactional manner

PROPAGATION_MANDATORY: uses the current transaction and throws an exception without it

PROPAGATION_REQURES_NEW: create a new transaction and suspend it if it currently exists

PROPAGATION_NOT_SUPPORTED: execute in a non-transactional manner, suspending if currently available

PROPAGATION_NEVER: execute in a non-transactional manner, suspending if any

PROPAGATION_NESTED: nested transactions

Transaction methods that make nested calls to each other in the same thread work in the same transaction, and if in different threads, transaction methods work in separate transactions under different threads.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report