java-mybaits-009-mybatis-spring-use, Sqlsessionfactorybean, business

Source: Internet
Author: User
Tags rollback

One, version restrictions

See Address: http://www.mybatis.org/spring/

Ii. Introduction to use 2.1, POM
<Dependency>  <groupId>Org.mybatis</groupId>  <Artifactid>Mybatis-spring</Artifactid>  <version>x.x.x</version></Dependency>
2.2. Sqlsessionfactorybean Creation

In the XML configuration file for Spring:

<id= "Sqlsessionfactory"  class= " Org.mybatis.spring.SqlSessionFactoryBean ">  <name=" DataSource "  ref=" DataSource "/></Bean  >

Note that sqlsessionfactory requires a DataSource (data source). This can be any DataSource, which is configured just like other Spring database connections.

2.3. Data Mapper

Suppose you define a data mapper interface as follows:

 Public Interface Usermapper {  @Select ("SELECT * from users WHERE id = #{userid}")  User getUser (@Param ("UserId"

Then you can use Mapperfactorybean to add the interface to Spring as follows:

<BeanID= "Usermapper"class= "Org.mybatis.spring.mapper.MapperFactoryBean">  < Propertyname= "Mapperinterface"value= "Org.mybatis.spring.sample.mapper.UserMapper" />  < Propertyname= "Sqlsessionfactory"ref= "Sqlsessionfactory" /></Bean>

Note that the specified mapper class must be an interface, not a specific implementation class. In this example, annotations are used to specify the SQL statement, but the MyBatis mapper XML file is also available.

Once configured, you can inject the mapper directly into your Business/service object in the same way as any other Spring bean. Mapperfactorybean handles the creation of sqlsession and closes it. If a Spring transaction is used, the session is committed or rolled back when the transaction completes. Eventually, any exception will be translated into Spring's DataAccessException exception.

Calling the MyBatis data method now requires only one line of code:

 Public class Implements Fooservice {    private  usermapper usermapper;      Public void Setusermapper (Usermapper usermapper) {        this. usermapper = usermapper;    }       Public User Dosomebusinessstuff (String userId) {        returnthis. Usermapper.getuser (userId);    }        }
Third, Sqlsessionfactorybean

In the basic MyBatis, the session factory can be created using Sqlsessionfactorybuilder. In Mybatis-spring, the Sqlsessionfactorybean is used instead.

3..1, creating

To create a factory bean, place the following code in the Spring XML configuration file:

 <  bean  id  = "Sqlsessionfactory"   class  = "Org.mybatis.spring.SqlSessionFactoryBean"   >  <  property  name  = "DataSource"   ref  = "DataSource"  />  </ bean  >  

Note that Sqlsessionfactorybean implements the spring Factorybean interface (refer to section 3.8 of the spring documentation), which shows that the bean that was eventually created by spring is not a sqlsessionfactory Bean itself,. Instead, the result of the method returned by the GetObject () of the factory class. In this case, Spring will create the Sqlsessionfactory object for you when the app starts, and then store it in Sqlsessionfactory name. In Java, the same code is:

New= Factorybean.getobject ();

In a general mybatis-spring usage, you do not need to use Sqlsessionfactorybean or its corresponding sqlsessionfactory directly. Instead, the session factory will be injected into Mapperfactorybean or other DAO (data Access object) that extends Sqlsessiondaosupport.

3.2. Properties

Sqlsessionfactory has a separate mandatory attribute, which is the DataSource of JDBC. This can be any DataSource, and its configuration should be the same as other Spring database connections.

A common property is configlocation, which is used to specify the MyBatis XML configuration file path. If the basic MyBatis configuration needs to be changed, then this is where it needs to be. Usually this will be part of <settings> or <typeAliases> .

Note that this configuration file does not need to be a full MyBatis configuration. Specifically, the transaction manager for any environment, data source, and MyBatis is ignored. Sqlsessionfactorybean will create its own, and it is necessary to use these values to customize the MyBatis environment.

If the MyBatis mapper XML file does not exist under the same path as the Mapper class, then another reason for needing a configuration file is that it is. There are two options for using this configuration. The first is to manually specify the classpath in the MyBatis XML configuration file using the <mappers> section. The second is to use the Mapperlocations property of the factory bean.

The Mapperlocations property uses a list of resource locations. This property can be used to specify the location of the MyBatis XML mapper file. Its value can include Ant styles to load all files in a directory, or recursively search all paths from the base path. Like what:

<BeanID= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean">  < Propertyname= "DataSource"ref= "DataSource" />  < Propertyname= "Mapperlocations"value= "Classpath*:sample/config/mappers/**/*.xml" /></Bean>

This loads all the MyBatis mapper XML files in the Sample.config.mappers package and its child packages from the classpath.

One of the properties that may be required in a container environment management transaction is Transactionfactoryclass. See section Fourth (section 4.2) for more information.

Added configuration Property after 1.3

<BeanID= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean">  < Propertyname= "DataSource"ref= "DataSource" />  < Propertyname= "Configuration">    <Beanclass= "Org.apache.ibatis.session.Configuration">      < Propertyname= "Mapunderscoretocamelcase"value= "true"/>    </Bean>  </ Property></Bean>
Iv. Business

One of the main reasons for using mybatis-spring is that it allows MyBatis to participate in Spring's transaction management. Instead of creating a new, specific transaction manager for MyBatis, Mybatis-spring takes advantage of the Datasourcetransactionmanager that exists in Spring.

Once spring's Platformtransactionmanager is configured, you can configure the transaction in spring in your usual way. @Transactional Annotations and AOP (aspect-oriented program, aspect-oriented programming, translator note)-style configurations are supported. A separate Sqlsession object will be created and used during transaction processing. When the transaction is complete, the session is committed or rolled back in the appropriate way.

Once the transaction is created, Mybatis-spring will manage the transaction transparently. There is no need for additional code in your DAO class.

4.1. Standard Business

To turn on spring transactions, simply create a Datasourcetransactionmanager object in the spring XML configuration file:

<id= "TransactionManager"  class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager ">  <  name = "DataSource" ref = "DataSource" /> </ Bean >

The specified DataSource can typically be any JDBC DataSource that you use with Spring. This includes the connection pool and the DataSource obtained through JNDI lookups.

Note that the DataSource specified for the transaction manager must be the same data source as the one used to create the Sqlsessionfactorybean, otherwise the transaction manager will not work.

4.2. Container Management Services

If you are using a JEE container and want spring to participate in container management transactions (Container managed TRANSACTIONS,CMT, translator note), then spring should use Jtatransactionmanager or its container Specifies the subclass to configure. The most convenient way to do this is to use Spring's transaction namespace:

</>

In this configuration, the MyBatis will be the same as other Spring transaction resources configured by CMT. Spring automatically uses any existing container transaction and appends a sqlsession to it. If you do not start a transaction, or if you need a transaction-based configuration, Spring opens a new container management transaction.

Note that if you want to use CMT instead of using Spring's transaction management, you must configure Sqlsessionfactorybean to use the basic MyBatis managedtransaction Factory instead of any other Spring transaction manager:

<BeanID= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean">  < Propertyname= "DataSource"ref= "DataSource" />  < Propertyname= "Transactionfactory">    <Beanclass= "Org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />  </ Property>  </Bean>
4.3. Programming transactions

The MyBatis sqlsession provides the specified method to handle a programmatic transaction. However, when using mybatis-spring, the bean will be injected using the Spring-managed sqlsession or mapper. That is, Spring is usually dealing with transactions.

You cannot raise the Sqlsession.commit (), Sqlsession.rollback (), or Sqlsession.close () method in the Spring-managed sqlsession. If you do this, you will throw a unsupportedoperationexception exception. Note that you cannot access those methods when you use the injected mapper.

Regardless of whether the JDBC connection is set to autocommit, the execution of the Sqlsession data method or any call to the Mapper method outside of the Spring transaction will be automatically committed.

If you want to programmatically control transactions, refer to section 10.6 of the Spring manual. This code shows how to handle transactions manually using the Platformtransactionmanager described in section 10.6.2.

New= txmanager.gettransaction (def); Try {  usermapper.insertuser (user);} Catch (MyException ex) {  txmanager.rollback (status);   Throw ex;} Txmanager.commit (status);

Note that this code shows a mapper, but it can also be used with sqlsession.

java-mybaits-009-mybatis-spring-use, Sqlsessionfactorybean, business

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.