java-mybaits-010-mybatis-spring-using sqlsession, inject mapper

Source: Internet
Author: User

I. Overview of Sqlsession

In MyBatis, you can use Sqlsessionfactory to create sqlsession. Once you have a session, you can use it to execute the mapping statement, commit or rollback the connection, and finally, when you no longer need it, you can close the session. After using mybatis-spring, you no longer need to use sqlsessionfactory directly, because your bean can be injected through a thread-safe sqlsession, automatically committed with Spring-based transaction configuration, rolled back, closed Sessi On

Note It is usually not necessary to use sqlsession directly. In most cases, Mapperfactorybean will inject the required mapper into the bean.

1.1, Sqlsessiontemplate

Sqlsessiontemplate is the core of mybatis-spring. This class is responsible for managing MyBatis's sqlsession, calling MyBatis's SQL method, and translating exceptions. Sqlsessiontemplate is thread-safe and can be used by multiple DAO shares.

When calling the SQL method, including the method returned from the Mapper Getmapper () method, Sqlsessiontemplate will ensure that the sqlsession used is related to the current Spring transaction. In addition, it manages the life cycle of the session, including the necessary shutdown, commit, or rollback operations.

The sqlsessiontemplate implements the Sqlsession interface, which means that there is no need to replace the MyBatis sqlsession in the code. Sqlsessiontemplate is typically used to replace the default MyBatis implementation of Defaultsqlsession because the template can participate in Spring transactions and is thread-safe when used by multiple injected mapper classes. Conversions between two classes in the same application can cause problems with data consistency.

Sqlsessiontemplate objects can be created using sqlsessionfactory as arguments to the constructor method.

<id= "Sqlsession"  class= "Org.mybatis.spring.SqlSessionTemplate"  >  <index= "0"  ref= " Sqlsessionfactory "/></bean>

This bean can now be injected directly into the DAO bean. You need to add a sqlsession attribute to the bean, just like the following code:

 Public class Implements Userdao {  private  sqlsession sqlsession;    Public void setsqlsession (sqlsession sqlsession) {    this. sqlsession = sqlsession;  }     Public user GetUser (String userId) {    return (User) Sqlsession.selectone (" Org.mybatis.spring.sample.mapper.UserMapper.getUser ", userId);}  }

Inject sqlsessiontemplate as follows:

<id= "Userdao"  class= "Org.mybatis.spring.sample.dao.UserDaoImpl"  >  <name= "sqlsession"  ref= " Sqlsession "/></bean>

Sqlsessiontemplate has a construction method that uses Executortype as a parameter. This allows you to create objects, such as a batch sqlsession, but uses the following Spring-configured XML files:

<BeanID= "Sqlsession"class= "Org.mybatis.spring.SqlSessionTemplate">  <Constructor-argIndex= "0"ref= "Sqlsessionfactory" />  <Constructor-argIndex= "1"value= "BATCH" /></Bean>

Now that all of your statements can be batched, the following statements can be used in DAO.

 Public void insertusers (user[] users) {   for  (User user:users) {     Sqlsession.insert (" Org.mybatis.spring.sample.mapper.UserMapper.insertUser ", user);   } }

Note that this configuration style can be used if the required execution method differs from the default Sqlsessionfactory setting.

The need to explain this form is that when this method is called, there cannot be a transaction that is running with a different executortype. Also be sure to use different actuators to invoke Sqlsessiontemplate in different transactions (such as propagation_requires_new) or completely out of one transaction.

1.2, Sqlsessiondaosupport

is an abstract support class that is used to provide you with sqlsession. Call the Getsqlsession () method and you will get a sqlsessiontemplate that can then be used to execute the SQL method as follows:

 Public class extends Implements Userdao {  public  User getUser (String userId) {    return (User) Getsqlsession (). SelectOne ("Org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);  }}

Usually Mapperfactorybean is the first choice for this class because it does not require additional code. However, this class is useful if you need to do other non-MyBatis work in DAO or need a specific class.

Sqlsessiondaosupport requires a sqlsessionfactory or Sqlsessiontemplate property to set. These are set explicitly or are assembled by Spring from the actuator. If both are set, then the Sqlsessionfactory is ignored.

Suppose the class Usermapperimpl is a subclass of Sqlsessiondaosupport, which can be configured in Spring as follows:

<id= "Usermapper"  class= " Org.mybatis.spring.sample.mapper.UserDaoImpl ">  < name  = "Sqlsessionfactory"  ref= "sqlsessionfactory"/></  Bean>
Second, inject the mapper

To replace code that manually uses Sqlsessiondaosupport or sqlsessiontemplate to write data Access Objects (DAO), Mybatis-spring provides a dynamic proxy implementation: Mapperfactorybean. This class allows you to inject the data mapper interface directly into your service layer bean. When using mappers, you can invoke them just as you would call your DAO, but you don't need to write any DAO implementation code, because mybatis-spring will create the proxy for you.

With injected mapper code, there is no direct dependency on mybatis,spring or mybatis-spring. Mapperfactorybean creates an agent that controls open and close sessions, translating arbitrary exceptions into Spring's dataaccessexception exceptions. In addition, if you need or participate in an existing active transaction, the agent will open a new Spring transaction.

2.1, Mapperfactorybean

The data mapper interface can be added 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>

The proxy class created by Mapperfactorybean implements the Usermapper interface and injects it into the application. Because the agent is created in the runtime environment (runtime, translator note), the specified mapper must be an interface, not a specific implementation class.

If the usermapper has a corresponding MyBatis XML mapper file, it will be parsed automatically by Mapperfactorybean if the XML file is in the same location as the class path and the Mapper class. It is not necessary to specify the mapper in the MyBatis configuration file unless the mapper's XML file is under a different classpath. You can refer to the Configlocation attribute of Sqlsessionfactorybean (chapter III) for more information.

Note that when Mapperfactorybean requires Sqlsessionfactory or sqlsessiontemplate. These can be set by their respective sqlsessionfactory or Sqlsessiontemplate properties, or they can be assembled from Spring. If the two properties are set, then the sqlsessionfactory is ignored because sqlsessiontemplate is required to have a session factory setting; The factory will be made by Mapperfactorybean. To use.

You can directly inject the mapper directly into the Business/service object in the same way that you inject any Spring bean:

<id= "Fooservice"  class= " Org.mybatis.spring.sample.mapper.FooServiceImpl ">  <name = "Usermapper" ref = "Usermapper" /> </ Bean >

This bean can be used directly in the application logic:

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

Note that there is no reference to sqlsession or MyBatis in this piece of code. There is no need to create, open or close the session of the Code, Mybatis-spring will come to care about it.

2.2, Mapperscannerconfigurer

It is not necessary to register all the mappers in the Spring XML configuration file. Instead, you can use a mapperscannerconfigurer, which will look for mappers under the classpath and automatically build them into Mapperfactorybean.

To create a mapperscannerconfigurer, you can add the following code to the Spring configuration:

<class= "Org.mybatis.spring.mapper.MapperScannerConfigurer">  <name= "Basepackage"  value= " Org.mybatis.spring.sample.mapper "/></bean>

The Basepackage property lets you set the basic package path for the Mapper interface file. You can use a semicolon or comma as a delimiter to set more than one package path. Each mapper will be recursively searched in the specified package path.

The Mapperscannerconfigurer property does not support the use of Propertyplaceholderconfigurer property substitution because it is loaded before Spring. However, you can use Propertiesfactorybean and Spel expressions as overrides.

Note that it is not necessary to specify Sqlsessionfactory or Sqlsessiontemplate, because Mapperscannerconfigurer will create Mapperfactorybean and then assemble automatically. However, if you use more than one DataSource, automatic assembly may fail. In this case, you can use the Sqlsessionfactorybeanname or Sqlsessiontemplatebeanname property to set the correct bean name. This is how it is configured, note that the bean name is required, not the bean's reference, and therefore the Value property replaces the usual ref:

<name= "Sqlsessionfactorybeanname"  value= "Sqlsessionfactory"  />

Mapperscannerconfigurer supports filtering by creating a mapper from the specified creation interface or annotations. The Annotationclass property specifies the name of the note to look for. The Markerinterface property specifies the parent interface to look for. If both are specified, the mapper added to the interface will match the two criteria. By default, both properties are null, so all interfaces given in the base package can be loaded as mappers.

The discovered mapper will use spring to name the auto-detect component (refer to the Spring Manual's 3.14.4) default naming policy. That is, if no annotations are found, it uses the non-uppercase, non-fully qualified class name of the mapper. However, if a @named annotation of @component or JSR-330 is found, it gets the name. Note that you can configure to Org.springframework.stereotype.Component, javax.inject.Named (if you use JSE 6) or your own annotations (which are definitely self-explanatory), which The sample annotations will be used as generators and name providers.

Covered

java-mybaits-010-mybatis-spring-using sqlsession, inject mapper

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.