"MyBatis Learning 14" MyBatis and Spring integration

Source: Internet
Author: User

The previous more than 10 posts summarize the relevant technologies in the development of MyBatis, but in practice they are integrated with spring, so here is a summary of the MyBatis and spring integration methods, which are tested after integration.

1. The integrated Environment

This is the old question, whether it is the development or integration, first of all, the environment must have, environment, in addition to the Java Environment and development environment, that is the jar package, about MyBatis and spring integrated jar package, I have uploaded to the download channel ==> portal
Import these jar packages into the Lib folder, then there are some files in the project, configuration files, Java files Ah, etc., first look at the structure of the entire project.

Below to complete all the integration steps.

2. Configuration Files

Before spring integration, MyBatis are managing their own data sources, and then sqlsessionfactory is our own to inject, now integrated, these will be given to spring to manage, to see the configuration in the Beans.xml file:

<?xml version= "1.0" encoding= "UTF-8"?><Beans xmlns="Http://www.springframework.org/schema/beans"       Xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"        Xmlns:context="Http://www.springframework.org/schema/context"       XMLNS:AOP="HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"        Xmlns:tx="Http://www.springframework.org/schema/tx"       xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/con Text/spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-4.2.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring- Tx.xsd ">    <!--load the Db.properties file under Classpath with some information about the database connection--    <context:property-placeholder location ="Classpath:db.properties"/>    <!--configuring data sources -    <bean id="DataSource" class="${datasource}"  Destroy-method="Close">        < property name="Driverclassname" value="${jdbc.driver}" />        < property name="url" value="${jdbc.url}" />         < property name="username" value="${jdbc.username}" />        < property name="password" value="${jdbc.password}" />         < property name="maxactive" value="Ten" />        < property name="Maxidle" value="5" />    </Bean>    <!--configuration Sqlsessionfactory,sqlsessionfactorybean is used to generate Sqlsessionfactory-    <bean id= "sqlsessionfactory" class=" Org.mybatis.spring.SqlSessionFactoryBean ">        <!--load the MyBatis global profile and put it in the MyBatis folder under Classpath.        < property name="Configlocation" value="Mybatis/sqlmapconfig.xml" />        <!--load the data source, using the data source configured above--        < property name="DataSource" ref="DataSource" />    </Bean></Beans>

Similar to spring and hibernate integration, the database connection information is loaded through the properties file, and then the configuration file is imported to configure Sessionfactory, Take a look at the db.properties and sqlmapconfig.xml files below.

#db.propertiesdataSource=org.apache.commons.dbcp.BasicDataSourcejdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc\:mysql\://localhost\:3306/mybatisjdbc.username=rootjdbc.password=root
<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration>    <settings><!--integration, do not set settngs .        <!--Open the delay-loaded switch--        <setting name="lazyloadingenabled" value="true"/>         <!--to change the active load to negative load, that is, delay load-        <setting name="aggressivelazyloading" value="false"/>         <!--turn on level two cache--        <setting name="cacheenabled" value="true"/>    </Settings>    <!--definition of aliases--    <typealiases>        < package name="Ssm.po"/>    </typealiases>    <mappers>        <mapper Resource="Sqlmap/user.xml" />        < package name="Ssm.mapper"/> <!--scan the entire package --    </mappers></configuration>
3. Configuration of DAO mode development

At the beginning we mentioned that there are two kinds of development in MyBatis, a DAO development way, a kind of mapper development way, the latter use more, but do not rule out the use of DAO way, so I summarize the two, first look at the configuration of DAO development.

3.1 Configuring User.xml

In the Sqlmap package there is a user.xml, which is for the user's operation of some configuration, here is the integration, so I wrote a statement, as follows:

<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!--namespace namespace, the role is to classify the SQL management, that is, SQL Isolation Note: The use of Mapper proxy method development, namespace has a special important role--<mapper namespace="Test">    <select id="Finduserbyid" parametertype="int" resulttype ="Ssm.po.User">SELECT * from user where id = #{id}</Select></mapper>

Just through the ID query users, if the test is successful, the integration is successful, after writing here, do not forget to load the map file in the Sqlmapconfig.xml, but the above has been loaded, that is <mapper resource="sqlmap/User.xml" /> .

3.2 Developing DAO and its implementation class

Next is the development of DAO and its implementation class, on a method, through the ID query users, first look at the DAO Method:

publicinterface UserDao {    //根据用户id查询用户信息    publicfindUserById(intthrows Exception;}

Then look at the implementation class:

public  class  userdaoimpl  extends  sqlsessiondaosupport  implements  userdao  {  @Override  public  User finduserbyid  (int  ID) throws  Exception {//inherit Sqlsessiondaosuppor T, sqlsession can be obtained by this.getsqlsession (), because Sqlsessiondaosupport has the method  sqlsession sqlsession = this . getsqlsession (); User user = Sqlsession.selectone ( "Test.finduserbyid" , id); return  user; }}

Here is the point: by DAO development, DAO implementation class in the implementation of the interface, the need to inherit the Sqlsessiondaosupport class, this class has the method of acquiring Sqlsession, Because Sqlsessionfactory is already configured in the Beans.xml file (write below), spring is automatically injected, inheriting the Sqlsessiondaosupport class and passing directly through the getsqlsession () method to obtain the sqlsession. Then you can manipulate the database.

3.3 Configuring DAO

The above also said, to get sqlsession must have sqlsessionfactory to do, this need spring to inject, so we configure the DAO in Beans.xml

<!-- 原始dao方法 --><bean id="userDao" class="ssm.dao.impl.UserDaoImpl">    <property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>

In this case, the DAO development method is integrated, the following to test:

 Public  class userdaoimpltest {    PrivateApplicationContext ApplicationContext;@Before     Public void setUp()throwsException {ApplicationContext =NewClasspathxmlapplicationcontext ("Classpath:beans.xml");//Get spring container}@Test     Public void Testfinduserbyid()throwsException {Userdao Userdao = (Userdao) Applicationcontext.getbean ("Userdao");//Get this beanUser user = Userdao.finduserbyid (1);    SYSTEM.OUT.PRINTLN (user); }}
4. Configuration of Mapper mode development

From the previous blog, the Mapper method development, Mapper.xml and Mapper.java files to be placed under a package, which is mainly placed under the Ssm.mapper package, the following look at two files:

4.1 Configuring Usermapper.xml and Usermapper.java
<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!--usermapper.xml file --<!--namespace namespace, the role is to classify the SQL management, that is, SQL Isolation Note: The use of Mapper proxy method development, namespace has a special role, Namespace=mapper interface address-- ><mapper namespace="Ssm.mapper.UserMapper">    <select id="Finduserbyid" parametertype="int"  Resulttype="user">SELECT * from user where id = #{id}</Select></mapper>
//mapper接口,相当于dao接口publicinterface UserMapper {    //根据id查询用户信息    publicfindUserById(intthrows Exception;}   

This is the same as before, no difficulty, note that the namespace in the XML should be written in the corresponding Java file fully qualified name.

4.2 Configuring Beans.xml

The mapper map and interface are already configured, so how does spring produce a proxy object? Spring is created by Mapperfactorybean to create proxy objects, see the following configuration:

<!--mapperfactorybean: Proxy objects generated based on Mapper interface--<bean id= "usermapper" class=" Org.mybatis.spring.mapper.MapperFactoryBean ">    < property name="Mapperinterface" value="Ssm.mapper.UserMapper" />    < property name= "sqlsessionfactory" ref=" Sqlsessionfactory " /></Bean>

From the configuration can be seen, using Mapperfactorybean to generate Mapper proxy object, first configure a mapperinterface, that is, you want spring to produce which mapper interface corresponding proxy object, So be sure to pass in the fully qualified name of the Mapper interface that we just wrote, and spring will know to create the corresponding proxy object. Of course, sqlsessionfactory is essential, otherwise how to produce sqlsession? The
test program will not write, the above test program to change, get "usermapper" this bean can be.
But the problem is, if there are a lot of mapper interfaces to the whole? Do you want to write a lot of these beans in the beans.xml? The answer is certainly not so, we can scan the package in Beans.xml, that is, tell spring, you put all the mapper interfaces in the specified package to me to generate a proxy object, as follows:

<!--Mapper Bulk Scan package, Scan out the Mapper interface from the Mapper package, automatically create proxy objects and register--> in the spring container;  < class  = " Org.mybatis.spring.mapper.MapperScannerConfigurer ";  <property  name  =" Basepackage "  value  = "Ssm.mapper" />  <property  name  = "sqlsessionfactorybeanname"  value  =  "sqlsessionfactory" />  </ bean ;   

As you can see from the configuration above, Spring uses Mapperscannerconfiger for mapper scanning. To scan successfully, you must follow the previously stated specification: Mapper.xml and Mapper.java Two filenames must be consistent and in the same directory. In this case, the ID of the mapper bean that is automatically scanned is the first letter of the Mapper class name lowercase. So the bean above has no id attribute, because this is based on the specific mapper interface. The basepackage is used to specify which packages to scan. This allows the mapper interface to be scanned in batches.
The test procedure is the same as above, and it is not written.
Here, spring and mybatis integration, here is just a simple integration, mainly to understand the integration of the process and methods, and do not use the spring AOP and transaction configuration, and so on after the specific project, I write it, first write so much ~
  

Related reading: http://blog.csdn.net/column/details/smybatis.html
Learning Note Source: Https://github.com/eson15/MyBatis_Study

-Willing to share and progress together!
--My Blog home: http://blog.csdn.net/eson_15

"MyBatis Learning 14" MyBatis and Spring integration

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.