Mapper development of Spring integrated MyBatis

Source: Internet
Author: User
Tags aliases

1.1 Integration Ideas

1, Sqlsessionfactory objects should be placed in the spring container as a singleton exists.

2. In the traditional DAO development mode, the Sqlsession object should be obtained from the spring container.

3. In mapper proxy form, the proxy object of mapper should be obtained directly from the spring container.

4, the database connection and database connection pool transaction management are given to the spring container to complete.

1.2 Integration of required JAR packages

1. Spring Jar Package

2. MyBatis Jar Package

3, Spring+mybatis integration package.

4, MySQL database drive jar package.

5. jar Package for database connection pool.

There's also a Spring-test Test pack (spring-test\4.1.1.release)

1.3 Steps for Integration

First step: Create a Java project.

Step two: Import the jar package. (The jar package mentioned above)

Step three: MyBatis configuration file Sqlmapconfig.xml

Fourth step: Write the Spring configuration file

1. Database connection and connection pool

2, transaction management (can not be configured temporarily)

3, Sqlsessionfactory objects, configured in the Spring container

4. The Mapeer proxy object or DAO implementation class is configured into the Spring container.

Fifth step: Writing a DAO or mapper file

Sixth step: Test.

Package Structure:

1.3.1 sqlmapconfig.xml

The original configuration in Sqlmapconfig.xml is managed by spring (except for aliases, Spring cannot process)

<?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>    <!--Configuring Pojo Aliases -    <typealiases>        <!--package Scan, default alias is class name, case insensitive -        < Packagename= "Com.mybatis.po"/>    </typealiases></Configuration>
1.3.2applicationcontext.xml
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:context= "Http://www.springframework.org/schema/context"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:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-4.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.0.xsd Http://www.springframework.org/schema/util http://www.springframework.org/schema/util/ Spring-util-4.0.xsd ">    <!--Load configuration file -    <Context:property-placeholder Location= "Classpath:db.properties" />    <!--Database Connection Pool -    <BeanID= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">        < Propertyname= "Driverclassname"value= "${jdbc.driver}" />        < Propertyname= "url"value= "${jdbc.url}" />        < Propertyname= "username"value= "${jdbc.username}" />        < Propertyname= "Password"value= "${jdbc.password}" />        < Propertyname= "Maxactive"value= "Ten" />        < Propertyname= "Maxidle"value= "5" />    </Bean>    <!--Mapper Configuration -    <!--let Spring management sqlsessionfactory use the MyBatis and spring integration packages -    <BeanID= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean">        <!--Database Connection Pool -        < Propertyname= "DataSource"ref= "DataSource" />        <!--load the global configuration file for MyBatis -        < Propertyname= "Configlocation"value= "Classpath:mybatis/sqlmapconfig.xml" />    </Bean>        <!--to create a mapper proxy object using the form of a scan package -    <Beanclass= "Org.mybatis.spring.mapper.MapperScannerConfigurer">        < Propertyname= "Basepackage"value= "Com.mybatis.mapper.UserMapper"></ Property>    </Bean></Beans>
1.3.3 db.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://Localhost:3306/mybatis? Characterencoding=utf-8jdbc.username=rootjdbc.password=123
1.4 Usermapper.java Class
 PackageCom.mybatis.mapper;Importjava.util.List;ImportCom.mybatis.po.User; Public InterfaceUsermapper {//query user information based on user ID     PublicUser Finduserbyid (intIdthrowsException; //querying the user list     PublicList<user> Finduserbyusername (String username)throwsException; //Add user Information     Public voidInsertuser (user user)throwsException;}
1.5 Usermapper.xml
<?xml version= "1.0" encoding= "UTF-8"? ><!DOCTYPE mapperpublic"-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace= " Com.mybatis.mapper.UserMapper "><!--get user information by ID--<select id=" Finduserbyid "parametertype=" int " Resulttype= "User" >Select* from user where id =#{id}</select><!--Custom Criteria Query user list-<select id= "Finduserbyusername" parametertype= "java.lang.String"Resulttype= "User" >Select* FROM user where username like '%${value}% ' </select><!--Add user--<insert id= "Insertuser" Paramete Rtype= "User" > <selectkey keyproperty= "id" order= "after" resulttype= "Java.lang.Integer" >Select last_insert_id ()</selectKey>INSERT INTO User (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})</insert></mapper>
1.6 Scan Package Form configuration Mapper
 <!--  Use the form of a scan package to create a mapper proxy object  -->  <  bean  class  = " Org.mybatis.spring.mapper.MapperScannerConfigurer " >  <  property  name  = "Basepackage"   value  = "Com.mybatis.mapper"  ></ property     >  </ bean  >  

The ID of each mapper proxy object is the class name, the first letter lowercase, and the "," interval between multiple packages.

1.7 Test methods
 Packagetest;Import Staticorg.junit.assert.*;Importjava.util.Date;Importjava.util.List;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;ImportCom.mybatis.mapper.UserMapper;ImportCom.mybatis.po.User; the @RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations= "Classpath:spring/applicationcontext.xml") Public classusermappertest {@AutowiredPrivateUsermapper Usermapper; @Test Public voidTestfinduserbyid ()throwsException {User User= Usermapper.finduserbyid (10);    SYSTEM.OUT.PRINTLN (user); } @Test Public voidTestfinduserbyusername ()throwsException {List<User> list = usermapper.finduserbyusername ("% sheet%"));  for(user user:list) {System.out.println (user); }} @Test Public voidTestinsertuser ()throwsException {User User=NewUser (); User.setaddress (Beijing); User.setbirthday (NewDate ()); User.setsex ("2"); User.setusername ("Korean Meimei");    Usermapper.insertuser (user); }}

Mapper development of Spring integrated MyBatis

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.