"Java" MyBatis and Spring Framework Integration (II.)

Source: Internet
Author: User
Tags aop

This article explains the implementation of the Spring injection mapper and transactional functions.

Injection Mapper Implementation

MyBatis can use the sqlsession getmapper (class<t> type) method to generate the implementation class directly from the specified mapper and mapping file. This makes it possible to invoke the Mapper's method for functional implementation without having to write the mapper's implementation class yourself.

Sqlsessiontemplate also has a corresponding getmapper () method, which leverages the components provided by mybatis-spring to inject mapper implementations directly into the business object without having to invoke the Getmapper () method each time, but in a configuration way. This is the preferred practice for data access operations that do not contain other non-MyBatis work.

Using the Mapperscannerconfigurer injection mapper

The following naming principles should be followed in the SQL mapping file:

1) The names of the mapped namespaces and mapper interfaces are the same.

2) The ID of the mapping element is the same as that of the Mapper interface.

First, the implementation class for the DAO interface can be removed.

The code for configuring the injection mapper is as follows:

    <!---    <class = " Org.mybatis.spring.mapper.MapperScannerConfigurer ">        <Name  = "Basepackage"  value= "Cn.xxxx.mapper"/>    </  Bean>

The Basepackage property specifies the baseline package for the scan, and Mapperscannerconfigurer will recursively scan all interfaces under the baseline package. If they are defined in the SQL mapping file, they are dynamically registered as Mapperfactorybean.

Attention:

1) The Basepackage property can contain multiple package names. Separate multiple package names with commas or semicolons.

2) All mapper implementations created by Mapperscannerconfigurer will be automatically injected into the Sqlsessionfactory instance.

3) If multiple Sqlsessionfactory instances are configured in the environment, automatic loading will not be possible. The dependent Sqlsessionfactory instance should be explicitly specified at this time. Here is an example

<Beanclass= "Org.mybatis.spring.mapper.MapperScannerConfigurer">        < Propertyname= "Sqlsessionfactorybeanname"value= "Sqlsessionfactory"/>
< Propertyname= "Basepackage"value= "Cn.bdqn.mapper" /> </Bean>

When a mapper is registered with a spring container, spring is named for its interface name, and the default rule is a non-fully qualified class name with the first letter lowercase. If the Usermapper type component is named Usermapper by default.

Use @Resource or @AutoWried annotations in a business logic implementation class to implement dependency injection of business components.

The context namespace needs to be introduced in the Spring configuration file, and a line of configuration code is added

    <!---    <base-package = "Cn.xxxx.service"  />

Declarative transactions

First, learn about the theoretical knowledge of transactions.

atomicity (atomicity): A transaction is an atomic operation that consists of a series of actions. The atomicity of a transaction ensures that the action is either complete or completely ineffective.

Consistency (consistency): When a transaction is complete, it must be that all data remains in a consistent state.

Isolation (Isolation): There is no impact between concurrent transaction executions, and operations within one transaction do not affect other transactions, which require the transaction isolation level to specify isolation.

Persistence (Durability): Once the transaction is complete, the database changes must be persisted.

Issues that may exist with transaction concurrency:

dirty reads: one transaction is read to another transaction uncommitted update data.
non-repeatable reads: one transaction reads the same row of data two times, but these two reads are different.
Phantom read: a transaction executes two queries, but the second query has more data rows than the first query.
missing updates: When you undo a transaction, the updated data that was committed by the other transaction is overwritten.

JDBC has customized five transaction isolation levels to handle transactional concurrency:

Transaction_none JDBC: Driver does not support transactions
Transaction_read_uncommitted: Allows dirty reads, non-repeatable reads, and Phantom reads.
Transaction_read_committed: Suppresses dirty reads, but allows non-repeatable reads and Phantom reads.
Transaction_repeatable_read: Suppress dirty Read and non-repeatable read, single run Phantom read.
Transaction_serializable: Suppresses dirty reads, non-repeatable reads, and Phantom reads.

The higher the isolation level, the lower the performance of concurrent execution of database transactions and the fewer operations you can handle.

Although the JDBC specification defines the above support behavior for transactions, each JDBC driver may have a different degree of support for the transaction by the database vendor.
For performance reasons we generally set the transaction_read_committed.

With spring, we don't have to deal with getting connections, closing connections, committing transactions, and rolling back, so we put more effort into dealing with the business.

In fact, Spring does not directly manage transactions, but rather provides a variety of transaction managers. They delegate the responsibility of the transaction management to the transaction of the relevant platform framework provided by Hibernate or JTA, and other persistence mechanisms.

This article focuses on the declarative transaction mechanism provided by Spring, which is implemented based on AOP, without having to write any transaction management code, all of which are done in the configuration file.

Configuration

You need to use the TX and AOP two namespaces, so first import these two namespaces

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"  xmlns:tx= "http// Www.springframework.org/schema/tx " Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0 . xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.0.xsd "><Beans/>

Configure a transaction manager component, where the transaction manager class provided by Spring is used Datasourcetransactionmanager

 <!--  define transaction manager  -->  <  bean  id  = "TransactionManager"   class  = "Org.springframework.jdbc.datasource.DataSourceTransactionManager"  >  <  property  name  = "DataSource"   ref  =" DataSource "/ >  </ bean  >  

The DataSource here is the data source component configured above.

You can configure transaction enhancements through <tx:advice> tags, set properties for transactions, and specify specific transaction rules for different business methods.

    <!--to set transaction properties for the specified transaction manager -    <Tx:adviceID= "Txadvice" transaction-manager= "TransactionManager" >        <!--defining properties, declaring transaction rules -        <tx:attributes>            <Tx:methodname= "add*"Propagation= "REQUIRED"Isolation= "DEFAULT"read-only= "false"  />            <Tx:methodname= "del*"Propagation= "REQUIRED"Isolation= "DEFAULT"read-only= "false" />            <Tx:methodname= "update*"Propagation= "REQUIRED"Isolation= "DEFAULT"read-only= "false" />            <Tx:methodname= "query*"Propagation= "Never"read-only= "true" />            <Tx:methodname= "get*"Propagation= "Never"read-only= "true" />        </tx:attributes>    </Tx:advice>

The Transaction-manager property references a transaction manager Bean

<tx:attributes> child tags are used to customize transaction properties. Transaction properties are set through the <tx:method> tab.

The name attribute in the <tx:method> tag is required to specify a matching method, and you can use a wildcard character (*). Other properties are optional and are used to specify a specific transaction rule.

propagation properties of Spring transactions
name value explain
Propagation_required 0 Supports the current transaction, and creates a new transaction if there is no current transaction. This is the most common choice and is also the propagation of spring's default transactions.
Propagation_supports 1 Supports the current transaction and is executed in a non-transactional manner if no transaction is currently in use.
Propagation_mandatory 2 Supports the current transaction and throws an exception if there is no current transaction.
Propagation_requires_new 3 Creates a new transaction, suspending the current transaction if the transaction currently exists.
propagation_not_supported 4 Executes the operation in a non-transactional manner, suspending the current transaction if a transaction is currently present.
Propagation_never 5 Executes in a non-transactional manner, throwing an exception if a transaction is currently present.
propagation_nested 6 Executes within a nested transaction if the transaction is currently present. If there is currently no transaction, do something similar to propagation_required.
isolation level for Spring transactions
name value explain
Isolation_default -1 This is a Platfromtransactionmanager default isolation level that uses the default transaction isolation level of the database. The other four correspond to the isolation level of JDBC
isolation_read_uncommitted 1 This is the lowest isolation level of a transaction, which allows another transaction to see the uncommitted data for this transaction. This isolation level produces dirty reads, non-repeatable reads, and Phantom reads.
isolation_read_committed 2 Ensure that a transaction modified data is committed before it can be read by another transaction. Another transaction cannot read uncommitted data for the transaction.
Isolation_repeatable_read 4 This level of transaction isolation prevents dirty reads and cannot be read repeatedly. However, Phantom reads may occur.
Isolation_serializable 8 This is the most cost-effective, but most reliable, transaction isolation level. Transactions are processed for sequential execution. In addition to preventing dirty reading, non-repeatable reading, but also avoids the phantom reading.

Finally, define the facets.

    <!--Defining Facets -    <Aop:config>        <!--Defining Pointcuts -        <Aop:pointcutexpression= "Execution (* cn.xxxx.service). *.*(..))"ID= "Pointcuttransaction" />        <!--combining transaction enhancements with Pointcuts -        <Aop:advisorAdvice-ref= "Txadvice"Pointcut-ref= "Pointcuttransaction"/>    </Aop:config>

Implementing declarative transactions with annotations

Spring supports the use of annotations to configure declarative transactions, using annotations that are @Transactional

First, you need to add support for annotations configured transactions in the Spring configuration file

    <transaction-manager= "TransactionManager"/>

adding annotations to the service business logic implementation class

@Transactional@Service ("Userserivce")publicclassimplements iuserservice{        @Autowired    @Qualifier ("Usermapper")    private  Usermapper Usermapper;    @Override    @Transactional (propagation=propagation.supports)    public list<user> queryusers () {        return  usermapper.queryusers ();    }}

Attention:

1) Add @Transactional annotations on the class to uniformly add transactions for all business methods of the class. If a business method requires different transaction rules, you can add @Transactional annotations on that business method to set them individually.

2) The use of transactions on query methods is not recommended and can affect the performance of queries.

When you use annotations to configure transactions, the properties that you use are consistent with the properties that are used in the Spring configuration file.

"Java" MyBatis and Spring Framework Integration (II.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.