MyBatis Study (iii)---mybatis and spring integration

Source: Internet
Author: User

Friends who want to understand the basics of MyBatis can pass through portals:

MyBatis Learning (i)---profiles, mapper interfaces, and dynamic SQL http://www.cnblogs.com/ghq120/p/8322302.html

MyBatis Learning (ii) association between---data sheets http://www.cnblogs.com/ghq120/p/8323918.html

The previous two articles described the use of mybatis separately and did not integrate with any framework. Using MyBatis to complete the database still has some templated code, such as closing the sqlsession, committing the transaction, and so on.

MyBatis and spring integrate only the DAO component interface without the implementation class, avoiding the method of explicitly invoking Sqlsession's related operations database, the commit of the transaction, and the shutdown of the sqlsession.

  The requirement for implementing MyBatis and spring consolidation and only the interface not implementing the class is that the primary file name of the DAO component interface and the primary file name of the mapping file have the same name, and under the same package, the namespace of the mapping file must be the fully qualified name of the DAO component interface. Flag the ID of the corresponding SQL statement must be the method name of the interface.

Mybatis+spring

The implementation of this project is also the user's additions and deletions to change

With spring, you do not need to use the tool class to get sqlsessionfactory and Sqlsession objects. Automatically obtained by configuring the bean element in the spring container.

The Spring container configuration file is as follows Applicationcontext.xml

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >        <!--Configure the data source to indicate the driver, URL, user name and password that are required to connect to the database, and connection pool-related information -    <BeanID= "Dbcpdatasource"class= "Org.apache.commons.dbcp.BasicDataSource">        < Propertyname= "Driverclassname"value= "Oracle.jdbc.driver.OracleDriver"></ Property>        < Propertyname= "url"value= "JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL"></ Property>        < Propertyname= "username"value= "Scott"></ Property>        < Propertyname= "Password"value= "Itcast"></ Property>        < Propertyname= "InitialSize"value= " the"></ Property>        < Propertyname= "Maxactive"value= "Ten"></ Property>        < Propertyname= "Maxidle"value= "3"></ Property>        < Propertyname= "Minidle"value= "2"></ Property>    </Bean>        <BeanID= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean">        < Propertyname= "Configlocation"value= "Mybatis-config.xml"></ Property>        < Propertyname= "DataSource"ref= "Dbcpdatasource"></ Property>    </Bean>        <!--Configure the DAO component interface's proxy class, which can only configure a single DAO component's proxy class, if you want to configure more than one, the bean element will appear multiple times, according to the ID to distinguish -    <BeanID= "Userdao"class= "Org.mybatis.spring.mapper.MapperFactoryBean">      < Propertyname= "Mapperinterface"value= "Com.ghq.model.dao.UserDao"></ Property>        < Propertyname= "Sqlsessionfactory"ref= "Sqlsessionfactory"></ Property>    </Bean></Beans>

Since the connection to the database has already been established in the spring container, there is no need to establish a connection to the database in the MyBatis configuration file,Mybatis-config.xml is configured as follows

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >  <Configuration>        <!--To define aliases in a configuration file, you can use aliases in the mapping file -    <typealiases>        < Packagename= "Com.ghq.model.entity"/>    </typealiases>      <!--registering a mapping file -  <mappers>    < Packagename= "Com.ghq.model.dao"/>  </mappers></Configuration>

The method in the DAO component is

 Public Interface Userdao {    // based on ambiguous name and gender query    list<user> getuserbynameandgender (map<string ,object> m);     // Bulk Delete users     Public Boolean delbatchuser (Uservo vo);}

Configuration file userdao.xml for DAO components

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd ">  <Mappernamespace= "Com.ghq.model.dao.UserDao">    <SelectID= "Getuserbynameandgender"ParameterType= "Java.util.Map"Resulttype= "User">SELECT * from User_tab<!--The where tab removes the first and by default, and if the input parameter is NULL, the Where condition is removed -    <where>        <ifTest= "Username ! = null and Username! =" ">and username like '%${username}% '</if>        <ifTest= "Gender!=null and gender! =" ">and gender = #{gender}</if>    </where>  </Select>    <DeleteID= "Delbatchuser"ParameterType= "Uservo">Delete from User_tab<where>      <ifTest= "Idlist!=null and Idlist.size () > 0">and ID in<foreachCollection= "Idlist"Item= "id"Open="("Close=")"Separator=",">#{id}</foreach>      </if>    </where>  </Delete></Mapper>

Unit Test

Using the spring container to create the object, you need to load the spring container, create the DAO component interface object, and invoke the method in the object.

 Public classTestmybatis {//get users based on conditions@Test Public voidTestgetuserbynameandgender () {sqlsession session=mybatisdb.getsession (); Userdao Userdao= Session.getmapper (Userdao.class); Map<String,Object> user =NewHashmap<string,object>(); User.put ("Username", "Zhang"); User.put ("Gender", "female"); List<User> ulist =userdao.getuserbynameandgender (user); if(Ulist! =NULL&& ulist.size () > 0) {             for(User uu:ulist) {System.out.println (UU); }        } Else{System.out.println ("There are no eligible users"); }            }    //ways to delete users in bulk@Test Public voidTestdelbatchuser () {ApplicationContext context=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Userdao Userdao= (Userdao) context.getbean ("Userdao"); Uservo Vo=NewUservo (); List<Integer> idlist =NewArraylist<integer>(); Idlist.add (8); Idlist.add (6);        Vo.setidlist (idlist); BooleanFlag =Userdao.delbatchuser (VO); if(flag) {System.out.println ("Delete Succeeded"); }Else{System.out.println ("Delete Failed"); }    }

MyBatis Study (iii)---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.