Mybatis与Spring集成

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

1、示例功能描述

2、创建工程

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

4、实例对象

5、配置文件

6、测试执行,输出结果 

1、示例功能描述

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

2、创建工程

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

 

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

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

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

订单表结构和数据如下:  

 

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

4、实例对象

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

User.java代码内容如下:

package com.tanlei.pojo;

/**
 * @author:Mr.Tan
 * @Create:2018-11-08-10-27
 **/
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代码内容如下:  

package com.tanlei.pojo;

/**
 * @author:Mr.Tan
 * @Create:2018-11-08-10-26
 **/
public class Order {
    private int orderId;
    private String orderNo;
    private float money;
    private int userId;
    private User user;

    public int getOrderId() {
        return orderId;
    }

    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }

    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;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

5.配置文件

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

applicationContext.xml  配置文件里最主要的配置: 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!--init-method="init" destroy-method="close">spring 容器在初始化bean 和容器销毁之前的所做的操作-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"
                  value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--dataSource属性指定要用到的连接池-->
        <property name="dataSource" ref="dataSource" />
        <!--configLocation属性指定mybatis的核心配置文件-->
        <property name="configLocation" value="config/Configure.xml" />
    </bean>

    <bean id="userMaper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
        <!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象-->
        <property name="mapperInterface" value="com.tanlei.mapper.UserMapper" />
    </bean>

</beans>

  

 配置文件 Configuration.xml 的内容如下: 

<?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标签 是写实体类的别名-->
    <typeAliases >
        <typeAlias alias="User" type="com.tanlei.pojo.User"></typeAlias>
        <typeAlias alias="Order" type="com.tanlei.pojo.Order"></typeAlias>
    </typeAliases>
    <!-- Mybatis和Spring 集成之后,这些可以完全删除(注释掉),
    数据库连接的管理交给 Spring 来管理 -->
    <!--
       <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
              <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"></property>
                <property name="username" value="root"></property>
                <property name="password" value="password"></property>
            </dataSource>
        </environment>
    </environments>-->

    <mappers>
        <!--  注释掉咯...
         <mapper resource="mybatis/user.xml"></mapper>-->
        <mapper resource="com/tanlei/mapper/UserMapper.xml" />
    </mappers>

</configuration>

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

<?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.tanlei.mapper.UserMapper">
    <!--为了返回list类型而定义的returnMap-->
    <!--id属性 ,resultMap标签的标识。
      type属性 ,返回值的全限定类名,或类型别名。-->
    <resultMap id="resultUser" type="User">
        <id  property="id" column="id"></id>
        <result column="username" property="username" />
        <result column="mobile" property="mobile" />
    </resultMap>

    <!-- User 联合 Order 查询 方法的配置 (多对一的方式)  -->
    <resultMap id="resultUserOrders" type="Order">
        <id property="orderId" column="order_id" />
        <result property="orderNo" column="order_no" />
        <result property="money" column="money" />
        <result property="userId" 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>
   <!--根据用户id查找订单和用户信息-->
    <select id="getUserOrders" parameterType="int" resultMap="resultUserOrders">
	   SELECT u.*,o.* FROM user u, order o
	          WHERE u.id=o.user_id AND u.id=#{id}
	</select>
    <!--根据用户id查找单个用户-->
    <select id="getUserById" parameterType="int"  resultMap="resultUser">
		SELECT *
		FROM user
		WHERE id=#{id}
	</select>

</mapper>

6、测试执行,输出结果

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

import com.tanlei.mapper.UserMapper;
import com.tanlei.pojo.Order;
import com.tanlei.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * @author:Mr.Tan
 * @Create:2018-11-08-10-28
 **/
public class Main {
    /*
    从类路径ClassPath中寻找指定的XML配置文件,找到并装载
   完成ApplicationContext的实例化工作。例如:
  //装载单个配置文件实例化ApplicationContext容器
  ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
  //装载多个配置文件实例化ApplicationContext容器
  String[] configs = {"bean1.xml","bean2.xml","bean3.xml"};
  ApplicationContext cxt = new ClassPathXmlApplicationContext(configs);
     */
    private  static ApplicationContext ctx;

    static {
        ctx=new ClassPathXmlApplicationContext("config/applicationContext.xml");
    }

    public static void main(String[] args) {
        UserMapper userMapper= (UserMapper) ctx.getBean("userMapper");
        // 测试id=1的用户查询,可根据数据库中的情况修改.
        User user =userMapper.getUserById(1);
        System.out.println("获取用户 ID=1 的用户名:"+user.getUsername());
        // 得到文章列表测试
        System.out.println("得到用户id为1的所有订单列表:");
        System.out.println("=============================================");
        List<Order> orders=userMapper.getUserOrders(1);
        for(Order order:orders){
            System.out.println("订单号:"+order.getOrderNo() + ",订单金额:" + order.getMoney());
        }
    }
}

  

 

 

posted @ 2018-11-08 16:47  言西早石头侠  阅读(175)  评论(0编辑  收藏  举报