MyBatis Integrated Spring Development explained

Source: Internet
Author: User

MyBatis Integrated Spring Development explained

Summary: Spring integrated MyBatis Development Summary There are two ways, the first is to configure the interface scan class in Applicationcontext.xml (while also scanning the Sql.xml configuration file) or inject the interface class ( Mapperscannerconfigurer, Mapperfactorybean These two in test to explain how to configure), the second is the native MyBatis, without interface development, and in the Applicationcontext.xml When configuring Sqlsessionfactory, configure the Conf.xml file to allow Mybatis to scan itself, thereby using native Mybatis in the program to do crud operations.

Note that in the previous article wrote the Mybatis annotation method is also an interface, in spring the interface and annotation method is not the same, the annotation mode when the interface is defined, to write the configuration in the interface, such as @select ("SELECT * FROM Users where id = #{id} "), and so on, do not need the corresponding Sql.xml configuration file, two in spring, write the interface, also need the corresponding sql.xml configuration file , and this file namespace is the corresponding interface full name, using Mapperscannerconfigurer After scanning the interface type, use the interface type when calling. Save () methods to implement CRUD.

1. List of items

2. Sequential source code
Package Com.bjsxt.bean;public class User {//shift+alt+sprivate int id;private String name;private int age;public User (int ID, String name, int age) {super (); this.id = Id;this.name = Name;this.age = age;} Public User () {super ();} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {return "User [id=" + ID + ", name=" + name + ", age=" + Age + "]";}}
Package Com.bjsxt.user.dao;import Java.util.list;import Com.bjsxt.bean.user;public interface Usermapper {void Save ( User user); void update (user user); void delete (int id); User FindByID (int id); List<user> findAll ();}
Package Com.bjsxt.user.dao;import Java.util.list;import Com.bjsxt.bean.user;public interface UserMapper2 {void Save ( User user); void update (user user); void delete (int id); User FindByID (int id); List<user> findAll ();}
<?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" ><!-- Spring integrated MyBatis namespace must be the full class name of the interface  --><mapper namespace= "Com.bjsxt.user.dao.UserMapper" ><insert Id= "Save" parametertype= "User" >insert into Users (name,age) values (#{name},#{age}) </insert></mapper>
<?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" ><!-- Spring integrated MyBatis namespace must be the full class name of the interface--><mapper namespace= "Com.bjsxt.user.dao.UserMapper2" ><insert id= " Save "parametertype=" User ">insert into Users (name,age) values (#{name},#{age}) </insert></mapper> 
Package Com.test;import Org.apache.ibatis.session.sqlsession;import org.apache.ibatis.session.SqlSessionFactory; Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.stereotype.component;import Com.bjsxt.bean.user;import Com.bjsxt.user.dao.usermapper;import com.bjsxt.user.dao.usermapper2;/** * configured This, <bean * class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" It is not necessary to configure * Org.mybatis.spring.mapper.MapperFactoryBean. The former configuration, automatic injection of different interface classes can be * The latter is also encapsulated into a single former, but also need to configure multiple, So with the former automatic sweep, all the interface and SQL configuration file *, in the following test class to inject an interface class, the configuration of the Mapperscannerconfigurer will automatically * parse out all the interface to provide the use of methods, Mapperscannerconfigurer No configuration ID, it doesn't make any sense. * */@Componentpublic class Test {@Autowiredprivate usermapper usermapper;@ Autowiredprivate UserMapper2 usermapper2;/** * The following two are testing implementations of different interface classes */@org. junit.testpublic void SaveUser1 () { ApplicationContext ac = new CLASSPATHXMLAPPLIcationcontext ("Applicationcontext.xml"); Sqlsessionfactory SF = (sqlsessionfactory) ac.getbean ("Sqlsessionfactory"); sqlsession session = Sf.opensession (); Test T = (test) ac.getbean ("test"); System.out.println (T.usermapper); T.usermapper.save (New User (-1, "Bursts 2", 1)); @org. junit.testpublic void SaveUser2 () {ApplicationContext ac = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); Sqlsessionfactory SF = (sqlsessionfactory) ac.getbean ("Sqlsessionfactory"); sqlsession session = Sf.opensession (); Test T = (test) ac.getbean ("test"); System.out.println (T.usermapper2); T.usermapper2.save (New User (-1, "Bursts 2", 1)); /** * application.xml Mybatis.spring.mapper.MapperFactoryBean Configuration Implementation and testing * if there are multiple interfaces that need to be configured many times, depending on the ID to identify the specific interface type */@ org.junit.Testpublic void SaveUser3 () {ApplicationContext ac = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); Sqlsessionfactory SF = (sqlsessionfactory) ac.getbean ("Sqlsessionfactory"); sqlsession session = Sf.opensession (); Usermapper mapper = (usermapper) AC.Getbean ("Usermapper"); Mapper.save (New User (-1, "Bursts 3", 1)); /** * Application.xml introduced the conf.xml configuration file Test */@org. junit.testpublic void SaveUser4 () {ApplicationContext AC = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); Sqlsessionfactory SF = (sqlsessionfactory) ac.getbean ("Sqlsessionfactory"); sqlsession session = Sf.opensession (true); Session.insert ("Com.bjsxt.user.dao.UserMapper.save", New User (-1, "wife", 27) );} public static void Main (string[] args) {new Test (). SaveUser4 ();}}

3, Applicationcontext.xml Configuration explained
<?xml version= "1.0" encoding= "UTF-8"? ><beansxsi:schemalocation= "http://www.springframework.org/schema/ Beans Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/ Context Http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/ Schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "xmlns:tx=" http://www.springframework.org/ Schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:p=" http://www.springframework.org /schema/p "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns=" http://www.springframework.org/schema/ Beans "><context:component-scan base-package=" com "></context:component-scan><!--1. Data source: Drivermanagerdatasource--><bean class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" id = "DataSource" ><property value= "Com.mysql.jdbc.Driver" name= "Driverclassname"/><property value= "JDBC: Mysql://localHost:3306/mybaits "name=" url "/><property value=" root "name=" username "/><property value=" 123456 "Name=" Password "/></bean><!--2. MyBatis's sqlsession factory: Sqlsessionfactorybean datasource/typealiasespackage--><bean class= " Org.mybatis.spring.SqlSessionFactoryBean "id=" sqlsessionfactory "><property name=" DataSource "ref=" DataSource "/><property value=" Com.bjsxt.bean "name=" Typealiasespackage "/><!-- The Configlocation property specifies MyBatis core profile--<property name= "configlocation" value= "Conf.xml"/> </bean><! --3. MyBatis automatic Scan loading SQL mapping file and interface with the type of injection you can directly use the method--><bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "><property value=" Com.bjsxt.user.dao "name=" Basepackage " /><property name= "Sqlsessionfactory" ref= "Sqlsessionfactory"/></bean><!--specifically configured with two interfaces mapper The following two configurations are, but this method is not applicable, to use it in the above automatic scanning configuration for--><bean id= "Usermapper" class= " Org.mybatis.spring.mapper.MapperFactoryBean "><pRoperty name= "Mapperinterface" value= "Com.bjsxt.user.dao.UserMapper" ></property><property name= " Sqlsessionfactory "ref=" sqlsessionfactory "></property></bean><bean id=" UserMapper2 "class=" Org.mybatis.spring.mapper.MapperFactoryBean "><property name=" Mapperinterface "value=" Com.bjsxt.user.dao.UserMapper2 "></property><property name=" sqlsessionfactory "ref=" sqlsessionfactory "></property></bean><!--4. Transaction management: Datasourcetransactionmanager--><beanclass= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "id=" manager "><property name=" DataSource " Ref= "DataSource"/></bean><!--5. Use declarative transactions--><tx:annotation-driven transaction-manager= "manager"/></beans>
4, Conf.xml Configuration explained
<?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><!--Configure an alias for an entity class--><typealiases><!--The former is an alias, and the latter is to omit the write of the package name in the XML, which can be written directly to the simple class name. ><typealias type= "Com.bjsxt.bean.User" alias= "_user"/> <package name= "Com.bjsxt.bean"/></ typealiases><!--Development: Development mode work: Working mode--><environments default= "development" ><environment Id= "Development" ><transactionmanager type= "JDBC"/><datasource type= "pooled" ><property name= " Driver "value=" Com.mysql.jdbc.Driver "/><property name=" url "value=" jdbc:mysql://localhost:3306/mybaits "/ ><property name= "username" value= "root"/><property name= "password" value= "123456"/></datasource ></environment></environments><mappers><mapper resource= "com/bjsxt/user/dao/ Usermapper.xml "/><mapper resource=" com/bjsxt/user/dao/uSermapper2.xml "/></mappers></configuration> 

5. lib

Packages required for spring integrated MyBatis

MyBatis Integrated Spring Development explained

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.