SSM社区SSM

MyBatis的关联查询

2018-05-02  本文已影响142人  嗷老板

创建数据库和表

/*
SQLyog Ultimate v8.32 
MySQL - 5.6.22-log : Database - mybatis
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybatis`;

/*Table structure for table `orders` */

DROP TABLE IF EXISTS `orders`;

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '下单用户id',
  `number` varchar(32) NOT NULL COMMENT '订单号',
  `createtime` datetime NOT NULL COMMENT '创建订单时间',
  `note` varchar(100) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

/*Data for the table `orders` */

insert  into `orders`(`id`,`user_id`,`number`,`createtime`,`note`) values (3,1,'1000010','2015-02-04 13:22:35',NULL),(4,1,'1000011','2015-02-03 13:22:41',NULL),(5,10,'1000012','2015-02-12 16:13:23',NULL);

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'王五',NULL,'2',NULL),(10,'张三','2014-07-10','1','北京市'),(16,'张小明',NULL,'1','河南郑州'),(22,'陈小明',NULL,'1','河南郑州'),(24,'张三丰',NULL,'1','河南郑州'),(25,'陈小明',NULL,'1','河南郑州'),(26,'王五',NULL,NULL,NULL);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
user(用户表)
orders(订单表)

两个表的关系:
  user表的主键id和orders表的外键user_id连接,从user表的角度来看,一个用户可以有多个订单,他们之间是一对多的关系;从orders表的角度来看,一个订单只属于一个用户,所以他们是一对一的关系

数据库表的关系

创建OrdersMapperQueryInterface接口及对应的xml文件

OrdersMapperQueryInterface接口

package connection;

public interface OrdersMapperQueryInterface {

}

OrdersMapperQueryInterface.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">
  
<!-- 使用接口代理的方式来开发dao操作数据库,一定要注意,
namespace这里不能再随便定义,一定要指向我们要执行的对应的接口 -->
<mapper namespace="connection.OrdersMapperQueryInterface"> 
</mapper>

创建OrdersMapperQueryInterface接口及对应的xml文件

UserMapperQueryInterface接口

package connection;

public interface UserMppaerQueryInterface {

}

UserMapperQueryInterface.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">
  
<!-- 使用接口代理的方式来开发dao操作数据库,一定要注意,
namespace这里不能再随便定义,一定要指向我们要执行的对应的接口 -->
<mapper namespace="connection.UserMapperQueryInterface"> 
</mapper>

配置SqlMapperConfig.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>
  <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/mybatis?charactorEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="connection/UserMapperQueryInterface.xml"/>
    <mapper resource="connection/OrdersMapperQueryInterface.xml"/>
  </mappers>
</configuration>

创建测试类,获取sqlSession对象

package connection;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

public class QueryTest {
    SqlSession sqlSession = null;
    
    /**
     * 获得sqlSession
     * @throws IOException
     */
    @Before
    public void getSession() throws IOException{
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = builder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
        sqlSession = build.openSession();
    }
    
}

一、一对一关联查询

  现在要通过一个订单的信息及对应的客户信息,需要使用一对一查询。实现这个查询,需要将user类的对象加入到orders类中,然后在mapper文件中,设置user类属性的映射。

创建User类和Orders类

User类

package domain;

import java.util.Date;

public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
                + address + "]";
    }

}

Orders类

package domain;

import java.util.Date;

public class Orders {
    private Integer id;
    private Integer userId;
    private String number;
    private Date createtime;
    private String note;
    
    //加入User类的对象
    private User user;
    
    
    public Orders() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public Date getCreatetime() {
        return createtime;
    }
    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    @Override
    public String toString() {
        return "Orders [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
                + ", note=" + note + ", user=" + user + "]";
    }
}

在OrdersMapperQueryInterface接口中定义查询方法

List<Orders> queryOrdersJoinUsers();

在OrdersMapperQueryInterface.xml配置文件中添加sql语句

<resultMap type="domain.Orders" id="ordersWithUser">
        <id column="id" property="id" />
        <result column="user_id" property="userId"/>
        <result column="number" property="number"/>
        <result column="createtime" property="createtime"/>
        <result column="note" property="note"/>
        <!-- 在mybatis当中通过association来表示我们一对一的关联关系
                注意:一定需要JavaType这个属性,来表明我们关联的对象
         -->
        <association property="user" javaType="domain.User">
            <result column="username" property="username"/>
            <result column="birthday" property="birthday"/>
            <result column="sex" property="sex"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>
    <select id="queryOrdersJoinUser" resultMap="ordersWithUser">
        select * from orders o left join user u on o.user_id = u.id
    </select>

进行测试

    @Test
    public void UserJoinOrders() throws Exception {
        OrdersMapperQueryInterface mapper = sqlSession.getMapper(OrdersMapperQueryInterface.class);
        List<Orders> queryOrdersJoinUser = mapper.queryOrdersJoinUser();
        for (Orders orders : queryOrdersJoinUser) {
            System.out.println(orders);
        }
    }

二、一对多关联查询

  现在我们要查询每个用户对应的订单情况,一个用户可以有多个订单,所以是一对多关联查询。

在User类中添加属性

User类

在UserMapperQueryInterface接口中定义查询方法

List<User> queryUserWithOrders();

在UserMapperQueryInterface.xml配置文件中添加sql语句

    <resultMap type="domain.User" id="userWithOrders">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
        <!-- 一对多的时候,通过collection来进行表示 
            在我们一对多的关联查询的时候,一定要使用ofType
        -->
        <collection property="orderList" ofType="domain.Orders">
            <result column="number" property="number"/>
            <result column="createtime" property="createtime"/>
            <result column="note" property="note"/>
        </collection>
    </resultMap>
    <select id="queryUserWithOrders" resultMap="userWithOrders">
        select * from user u left join orders o on u.id = o.user_id where u.id=1
    </select>

进行测试

    @Test
    public void OrdersJoinUser() throws Exception {
       UserMppaerQueryInterface mapper = sqlSession.getMapper(UserMppaerQueryInterface.class);
       List<User> queryUserWithOrders = mapper.queryUserWithOrders();
       for (User user : queryUserWithOrders) {
           System.out.println(user.getUsername());
           List<Orders> ordersList = user.getOrdersList();
           for (Orders orders : ordersList) {
            System.out.println(orders);
        }
        
    }
    }
上一篇 下一篇

猜你喜欢

热点阅读