Mybatis与Spring集成

CoffeeScript ww9992019com 发表于 1 周前

<div style="width:100%;float:left;" class="article-content">

                <input type="hidden" name="article_id" id="article_id" value="7732">
                <input type="hidden" name="catid" id="catid" value="0">

                <p>

在前面的教程文章中,前面讲到有关 mybatis 连接数据库,然后进行进行数据增删改查,以及多表联合查询的例子,但很多的项目中,通常会用 spring 这个粘合剂来管理 datasource 等。充分利用 spring 基于接口的编程,以及aop ,ioc 带来的方便。用 spring 来管理 <a href="http://www.yiibai.com/mybatis/" target="_blank">mybatis</a> 与管理 hibernate 有很多类似的地方。在这一节中,我们重点介绍数据源管理以及 bean 的配置。

</p>

<p>

整个Mybatis与Spring集成示例要完成的步骤如下:

</p>

<p>

1、示例功能描述

</p>

<p>

2、创建工程

</p>

<p>

3、数据库表结构及数据记录

</p>

<p>

4、实例对象

</p>

<p>

5、配置文件

</p>

<p>

6、测试执行,输出结果

</p>

<h2>

<span>1、示例功能描述</span>

</h2>

<p>

在本示例中,需要完成这样的一个简单功能,即,指定一个用户(ID=1),查询出这个用户的基本信息,并关联查询这个用户的所有订单。

</p>

<h2>

<span>2、创建工程</span>

</h2>

<p>

 首先创建一个工程的名称为:mybatis07-spring,在 src 源代码目录下建立文件夹 config,并将原来的 mybatis 配置文件 Configuration.xml 移动到这个文件夹中, 并在 config 文家夹中建立 Spring 配置文件:applicationContext.xml。工程结构目录如下:

</p>

<p>

<img src="/uploads/tutorial/201509/1-150930220H0106.png" width="308" height="360" title="Mybatis与Spring集成" alt="Mybatis与Spring集成">

</p>

<h2>

<span>3、数据库表结构及数据记录</span>

</h2>

<p>

在本示例中,用到两个表:用户表和订单表,其结构和数据<span>记录</span>如下:

</p>

<pre class="prettyprint">CREATE TABLE user (

id int(10) unsigned NOT NULL AUTO_INCREMENT,

username varchar(64) NOT NULL DEFAULT '',

mobile varchar(16) 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');</pre>

订单表结构和数据如下:

<pre class="prettyprint">CREATE TABLE order (

order_id int(10) unsigned NOT NULL AUTO_INCREMENT,

user_id int(10) unsigned NOT NULL DEFAULT '0',

order_no varchar(16) 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', '1519289091', '290.80');

INSERT INTO order VALUES ('3', '1', '1509294321', '919.90');

INSERT INTO order VALUES ('4', '1', '1601232190', '329.90');

INSERT INTO order VALUES ('5', '1', '1503457384', '321.00');

INSERT INTO order VALUES ('6', '1', '1598572382', '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');

INSERT INTO order VALUES ('10', '1', '1932428723', '5888.00');

INSERT INTO order VALUES ('11', '1', '2390423712', '3219.00');

INSERT INTO order VALUES ('12', '1', '4587923992', '123.00');

INSERT INTO order VALUES ('13', '1', '4095378812', '421.00');

INSERT INTO order VALUES ('14', '1', '9423890127', '678.00');

INSERT INTO order VALUES ('15', '1', '7859213249', '7689.00');

INSERT INTO order VALUES ('16', '1', '4598450230', '909.20');</pre>

<h2>

<span><span>4、实例对象</span><br>

</span>

</h2>

<p>

用户表和订单表分别对应两个实例对象,分别是:User.java 和 Order.java,它们都在 com.yiibai.pojo 包中。

</p>

<p>

<span>User.java代码内容如下:</span>

</p>

<pre class="prettyprint lang-java">package com.yiibai.pojo;

import java.util.List;

/**

*/

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;

}

}</pre>

<p>

<span><span>Order</span>.java代码内容如下:</span>

</p>

<p>

<span> </span>

</p>

<pre class="prettyprint lang-java">package com.yiibai.pojo;

/**

*/

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;

}

}</pre>

<h2>

<span>5、配置文件</span>

</h2>

<p>

这个实例中有三个重要的配置文件,它们分别是:<span>applicationContext.xml , <span>Configuration.xml 以及 UserMaper.xml。</span></span>

</p>

<p>

<span>applicationContext.xml  </span>配置文件里最主要的配置:

</p>

<pre class="prettyprint lang-xml">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;

&lt;!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;

&lt;configuration&gt;

&lt;typeAliases&gt;

    &lt;typeAlias alias="User" type="com.yiibai.pojo.User" /&gt;

    &lt;typeAlias alias="Order" type="com.yiibai.pojo.Order" /&gt;

&lt;/typeAliases&gt;

&lt;!-- MybatisSpring 集成之后,这些可以完全删除(注释掉),数据库连接的管理交给 Spring 来管理 --&gt;

&lt;!--

    &lt;environments default="development"&gt; &lt;environment id="development"&gt;

    &lt;transactionManager type="JDBC"/&gt; &lt;dataSource type="POOLED"&gt; &lt;property

    name="driver" value="com.mysql.jdbc.Driver"/&gt; &lt;property name="url"

    value="jdbc:mysql://127.0.0.1:3306/yiibai?characterEncoding=utf8" /&gt;

    &lt;property name="username" value="root"/&gt; &lt;property name="password"

    value=""/&gt; &lt;/dataSource&gt; &lt;/environment&gt; &lt;/environments&gt;

--&gt;

&lt;mappers&gt;

    &lt;mapper resource="com/yiibai/maper/UserMaper.xml" /&gt;

&lt;/mappers&gt;

&lt;/configuration&gt;</pre>

<p>

配置文件 <span>Configuration.xml 的内容如下:</span>

</p>

<p>

<span> </span>

</p>

<pre class="prettyprint lang-xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;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/spring-beans-3.0.xsd

        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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-jee-3.0.xsd

        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

default-autowire="byName" default-lazy-init="false"&gt;



&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt;

    &lt;property name="driverClassName" value="com.mysql.jdbc.Driver" /&gt;

    &lt;property name="url"

        value="jdbc:mysql://127.0.0.1:3306/yiibai?characterEncoding=utf8" /&gt;

    &lt;property name="username" value="root" /&gt;

    &lt;property name="password" value="" /&gt;

&lt;/bean&gt;



&lt;bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"&gt;

    &lt;!--dataSource属性指定要用到的连接池--&gt;

    &lt;property name="dataSource" ref="dataSource" /&gt;

    &lt;!--configLocation属性指定mybatis的核心配置文件--&gt;

    &lt;property name="configLocation" value="config/Configuration.xml" /&gt;

&lt;/bean&gt;



&lt;bean id="userMaper" class="org.mybatis.spring.mapper.MapperFactoryBean"&gt;

    &lt;!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例--&gt;

    &lt;property name="sqlSessionFactory" ref="sqlSessionFactory" /&gt;

    &lt;!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象--&gt;

    &lt;property name="mapperInterface" value="com.yiibai.maper.UserMaper" /&gt;

&lt;/bean&gt;

&lt;/beans&gt; </pre>

<p>

<span>UserMaper.xml </span>用于定义查询和数据对象映射,其内容如下:

</p>

<pre class="prettyprint lang-xml">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;

&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;

&lt;mapper namespace="com.yiibai.maper.UserMaper"&gt;

    &lt;!-- 为了返回list 类型而定义的returnMap --&gt;

&lt;resultMap type="User" id="resultUser"&gt;

    &lt;id column="id" property="id" /&gt;

    &lt;result column="username" property="username" /&gt;

    &lt;result column="mobile" property="mobile" /&gt;

&lt;/resultMap&gt;



&lt;!-- User 联合 Order 查询 方法的配置 (多对一的方式)  --&gt;

&lt;resultMap id="resultUserOrders" type="Order"&gt;

    &lt;id property="orderId" column="order_id" /&gt;

    &lt;result property="orderNo" column="order_no" /&gt;

    &lt;result property="money" column="money" /&gt;

    &lt;result property="userId" column="user_id" /&gt;



    &lt;association property="user" javaType="User"&gt;

        &lt;id property="id" column="id" /&gt;

        &lt;result property="username" column="username" /&gt;

        &lt;result property="mobile" column="mobile" /&gt;

    &lt;/association&gt;

&lt;/resultMap&gt;



&lt;select id="getUserOrders" parameterType="int" resultMap="resultUserOrders"&gt;

   SELECT u.*,o.* FROM `user` u, `order` o

          WHERE u.id=o.user_id AND u.id=#{id}

&lt;/select&gt;



&lt;select id="getUserById" resultMap="resultUser" parameterType="int"&gt;

    SELECT *

    FROM user

    WHERE id=#{id}

&lt;/select&gt;

&lt;/mapper&gt;
</pre>

<h2>

<span>6、测试执行,输出结果</span>

</h2>

<p>

我们创建一个测试类为:Main.java , 就在 src 目录中。其代码如下:

</p>

<pre class="prettyprint lang-java">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;

/**

*/

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");

    // 测试id=1的用户查询,可根据数据库中的情况修改.

    User user = userMaper.getUserById(1);

    System.out.println("获取用户 ID=1 的用户名:"+user.getUsername());



    // 得到文章列表测试

    System.out.println("得到用户id为1的所有订单列表:");

    System.out.println("=============================================");

    List&lt;Order&gt; orders = userMaper.getUserOrders(1);



    for (Order order : orders) {

        System.out.println("订单号:"+order.getOrderNo() + ",订单金额:" + order.getMoney());

    }



}

}
</pre>

<p>

运行结果如下:

</p>

<pre class="prettyprint lang-java">log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).

log4j:WARN Please initialize the log4j system properly.

获取用户 ID=1 的用户名:yiibai

得到用户id为1的所有订单列表:

=============================================

订单号:1509289090,订单金额:99.9

订单号:1519289091,订单金额:290.8

订单号:1509294321,订单金额:919.9

订单号:1601232190,订单金额:329.9

订单号:1503457384,订单金额:321.0

订单号:1598572382,订单金额:342.0

订单号:1500845727,订单金额:458.0

订单号:1508458923,订单金额:1200.0

订单号:1504538293,订单金额:2109.0

订单号:1932428723,订单金额:5888.0

订单号:2390423712,订单金额:3219.0

订单号:4587923992,订单金额:123.0

订单号:4095378812,订单金额:421.0

订单号:9423890127,订单金额:678.0

订单号:7859213249,订单金额:7689.0

订单号:4598450230,订单金额:909.2</pre>

<p>

代码下载:<a href="http://pan.baidu.com/s/1wRpOq" target="_blank">Mybatis与Spring集成</a>

</p>

                <br>
                <p style="text-align:center;float:left;width:100%;margin-top:24px;margin-bottom:18px;">
                        <button class="layui-btn layui-btn-danger" id="btn-reward"> ¥ 我要打赏 </button>  
                        <button class="layui-btn" id="article-perfect">
                            <i class="layui-icon layui-icon-edit"></i>教程纠错
                        </button>
                        <button class="layui-btn layui-btn-normal" id="action-collection">
                            <i class="layui-icon layui-icon-rate"></i>收藏
                        </button>
                </p>



                <div style="width:100%;margin-bottom: 16px; height: 32px;margin-top:18px;float:left;">

                    <span style="float:left;">上一篇:<a href="http://f2e.im/u/ww9992019com" title="Mybatis 多对多"><i class="layui-icon"></i>
                            Mybatis 多对多</a></span>
                                            <span style="float:right;">下一篇:<a href="http://f2e.im/u/ww9992019com" style="float:right;" title="下一篇:MyBatis整合Spring MVC"><i class="layui-icon"></i>
                            MyBatis整合Spring MVC</a></span>
                                            <div id="googlead" style="float:left;margin-top:8px;">
                        <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
                        <!-- yiibai下方 -->
                        <ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1090193214637198" data-ad-slot="6494738921"></ins>
                        <script>
                            (adsbygoogle = window.adsbygoogle || []).push({});
                        </script>
                    </div>
                </div>

                <div style="width:100%;margin-top:18px;float:left;">


            </div>
暂无回复,说出你的观点吧
登录后即可参与回复