MyBatis integration with spring (easy tutorial)

Source: Internet
Author: User
Tags aop log4j

The steps to complete the MyBatis and Spring Integration sample are as follows:

1. Example function description

2. Create the Project

3. database table structure and data record

4. Instance objects

5. Configuration Files

6, test execution, output results

1. Example function description

In this example, you need to complete a simple function of specifying a user (id=1), querying the user's basic information, and correlating all orders for that user.

2. Create the Project

First create a project name: mybatis07-spring, in the SRC source code directory under the folder Config, and the original MyBatis configuration file Configuration.xml moved to this folder, and in the Config home folder set up S Pring configuration file: Applicationcontext.xml. The engineering structure directory is as follows:

3. database table structure and data record

In this example, two tables are used: the user table and the order table, with their structure and data recorded as follows:

CREATE TABLE ' user ' (  ' id ' int () unsigned not null auto_increment,  ' username ' varchar (") ' NOT null DEFAULT ', 
    ' mobile ' varchar (+) not NULL default ',  PRIMARY KEY (' id ')) engine=innodb auto_increment=3 DEFAULT Charset=utf8; --------------------------------Records of user------------------------------INSERT into ' user ' VALUES (' 1 ', ' Yiibai ') , ' 13838009988 '); INSERT into ' user ' VALUES (' 2 ', ' Saya ', ' 13838009988 ');

The order table structure and data are as follows:

CREATE TABLE ' order ' (' order_id ' int (ten) unsigned NOT null auto_increment, ' user_id ' int (ten) unsigned NOT NULL DEFAULT  ' 0 ', ' order_no ' varchar (+) not NULL default ", ' Money ' float (10,2) unsigned default ' 0.00 ', PRIMARY KEY (' order_id ')) Engine=innodb auto_increment=17 DEFAULT Charset=utf8;--------------------------------Records of order-------------- ----------------INSERT INTO ' order ' values (' 1 ', ' 1 ', ' 1509289090 ', ' 99.90 '); insert into ' order ' values (' 2 ', ' 1 ', ' 151928 9091 ', ' 290.80 '); insert into ' order ' values (' 3 ', ' 1 ', ' 1509294321 ', ' 919.90 '); insert into ' order ' values (' 4 ', ' 1 ', ' 1601 232190 ', ' 329.90 '); insert into ' order ' values (' 5 ', ' 1 ', ' 1503457384 ', ' 321.00 '); insert into ' order ' values (' 6 ', ' 1 ', ' 15 98572382 ', ' 342.00 '); insert into ' order ' values (' 7 ', ' 1 ', ' 1500845727 ', ' 458.00 '); insert into ' order ' values (' 8 ', ' 1 ', ' 1508458923 ', ' 1200.00 '); insert into ' order ' values (' 9 ', ' 1 ', ' 1504538293 ', ' 2109.00 ') and insert INTO ' order ' values (' 10 ', ' 1 ', ' 1932428723 ', ' 5888.00 'INSERT INTO ' order ' values (' One ', ' 1 ', ' 2390423712 ', ' 3219.00 '); insert into ' order ' values (' 12 ', ' 1 ', ' 4587923992 ', ' 12  INSERT INTO ' order ' values (' 3.00 ', ' 1 ', ' 4095378812 ', ' 421.00 ') and insert INTO ' order ' values (' 14 ', ' 1 ', ' 9423890127 ', ' 678.00 '); insert into ' order ' values (' ['] ', ' 1 ', ' 7859213249 ', ' 7689.00 '); insert into ' order ' values (' 16 ', ' 1 ', ' 4598450 230 ', ' 909.20 ');
4. Instance objects

The user table and the order table correspond to two instance objects, respectively: User.java and Order.java, which are all in the Com.yiibai.pojo package.

User.java code content is as follows:

Package Com.yiibai.pojo;import java.util.list;/**  * @describe: User * @author: Yiibai  * @version: V1.0 * @copyrig  HT http://www.yiibai.com */Public  class User {private int id;private string username;private string mobile;public int GetId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String Getmobile () {return mobile;} public void Setmobile (String mobile) {this.mobile = Mobile;}}

Order.java code content is as follows:

Package com.yiibai.pojo;/** * @describe: Order-Order * @author: Yiibai * @version: V1.0 * @copyright http://www.yiibai.com */public class Order {private int orderid;private String orderno;private float money;private int userid;private user user; public int getUserId () {return userId;} public void Setuserid (int userId) {this.userid = userId;} public int Getorderid () {return orderId;} public void Setorderid (int orderId) {this.orderid = orderId;} Public User GetUser () {return user;} public void SetUser (user user) {this.user = user;} Public String Getorderno () {return orderno;} public void Setorderno (String orderno) {this.orderno = OrderNo;} public float Getmoney () {return money;} public void Setmoney (float money) {This.money = money;}}
5. Configuration Files

There are three important configuration files in this instance: Applicationcontext.xml, Configuration.xml, and Usermaper.xml.

The most important configuration in the Applicationcontext.xml configuration file:

<?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><typealiases><typealias alias= "User" type= "Com.yiibai.pojo.User"/><typealias alias= "Order" type= "Com.yiibai.pojo.Order"/></typealiases><!--MyBatis and spring are integrated, these can be completely removed (commented out), Management of database connections give Spring to manage--><!--<environments default= "Development" > <environment id= "Development" > <transactionmanager type= "JDBC"/> <datasource type= "Pooled" > <propertyname= "Driver" value= " Com.mysql.jdbc.Driver "/> <property name=" url "value=" jdbc:mysql://127.0.0.1:3306/yiibai?characterencoding= UTF8 "/><property name=" username "value=" root "/> <property name=" password "value=" "/> </datasource > </environment> </environments>--><mappers><mapper resource= "com/yiibai/maper/ Usermaper.xml "/></mappers></configuration>

The contents of the configuration file Configuration.xml are as follows:

<?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:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spri Ng-beans-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-a Op-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring -context-3.0.xsd Http://www.springframework.org/schema/jee Http://www.springframework.org/schema/jee/spring-j Ee-3.0.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema/tx/spring-tx-3.0.xs D "default-autowire=" ByName "default-lazy-init=" false "><Bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" ><property name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/><property name= "url" value= "jdbc:mysql://127.0.0.1:3306/yiibai?characterencoding= UTF8 "/><property name=" username "value=" root "/><property name=" password "value=" "/></bean> <bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" ><!-- The DataSource property specifies the connection pool to use--><property name= "DataSource" ref= "DataSource"/><!-- The Configlocation property specifies the core configuration file for MyBatis--><property name= "configlocation" value= "Config/configuration.xml"/> </bean><bean id= "Usermaper" class= "Org.mybatis.spring.mapper.MapperFactoryBean" > <!-- The Sqlsessionfactory property specifies the Sqlsessionfactory instance to use--><property name= "sqlsessionfactory" ref= "sqlSessionFactory"/ ><!--Mapperinterface property specifies the Mapper interface for implementing this interface and generating mapper objects--><property name= "Mapperinterface" value= " Com.yiibai.maper.UserMaper "/&GT;&LT;/BEAN&GT;&LT;/BEANS&GT  

The usermaper.xml is used to define the query and data object mappings, which are as follows:

<?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" >< Mapper namespace= "Com.yiibai.maper.UserMaper" ><!--the Returnmap--><resultmap type= "User" ID defined to return the list type = "Resultuser" > <id column= "id" property= "id"/> <result column= "username" property= "username"/&        Gt <result column= "mobile" property= "mobile"/> </resultMap> < configuration of the User federated Order Query method (many-to-one way)--&gt ; <resultmap id= "Resultuserorders" type= "Order" > <id property= "orderId" column= "order_id"/> <result p Roperty= "OrderNo" column= "Order_no"/> <result property= "Money" column= "Money"/> <result property= "user ID "column=" user_id "/> <association property=" user "javatype=" user "> <id property=" id "column=" ID "/> <result property=" username "column=" username "/> <result property=" mObile "column=" mobile "/> </association> </resultMap> <select id=" getuserorders "parameter type= "int" resultmap= "resultuserorders" > select u.*,o.* from ' User ' U, ' order ' O WHERE u.id=o.user_id and U . Id=#{id}</select><select id= "Getuserbyid" resultmap= "Resultuser" parametertype= "int" >SELECT *FROM Userwhere id=#{id}</select> </mapper>
6, test execution, output results

We create a test class as: Main.java, just in the SRC directory. The code is as follows:

Import Java.util.list;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.yiibai.maper.usermaper;import Com.yiibai.pojo.order;import com.yiibai.pojo.user;/** * Description * @author Yiibai * @date 2015-4-12 * @copyright http:/ /www.yiibai.com * @email [email protected] * @version 1.0 */public class Main {private static ApplicationContext ctx; static {CTX = new Classpathxmlapplicationcontext ("Config/applicationcontext.xml");} public static void Main (string[] args) {Usermaper usermaper = (usermaper) ctx.getbean ("Usermaper");//test id=1 user query, Can be modified according to the situation in the database. User user = Usermaper.getuserbyid (1); System.out.println ("Get user id=1 User name:" +user.getusername ());//Get the article List Test System.out.println ("Get a list of all orders with user ID 1:"); System.out.println ("============================================="); list<order> orders = usermaper.getuserorders (1); for (order order:orders) {System.out.println ("Order Number:" + Order.getorderno () + ", Order Amount:" + OrdEr.getmoney ());}}} 

The results of the operation are as follows:

Log4j:warn No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext) . Log4j:warn Please initialize the log4j system properly. Get user id=1 Username: Yiibai Get a list of all orders with user ID 1: ========================= ==================== Order Number: 1509289090, Order Amount: 99.9 order number: 1519289091, Order Amount: 290.8 order Number: 1509294321, Order Amount: 919.9 order Number: 1601232190, Order Amount: 329.9 order Number: 1503457384, Order Amount: 321.0 Order number: 15985723 82, Order Amount: 342.0 order Number: 1500845727, Order Amount: 458.0 order Number: 1508458923, Order Amount: 1200.0 order Number: 1504538293, Order Amount: 2109.0 order Number: 1932428723, Order Amount: 5888.0 Order Number: 2 390423712, Order Amount: 3219.0 order Number: 4587923992, Order Amount: 123.0 order Number: 4095378812, Order Amount: 421.0 order Number: 9423890127, Order Amount: 678.0 order Number: 7859213249, Order Amount: 7689 .0 Order Number: 4598450230, Order Amount: 909.2

MyBatis integration with spring (easy tutorial)

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.