MyBatis的關聯(lián)查詢

創(chuàng)建數(shù)據(jù)庫和表

/*
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 '創(chuàng)建訂單時間',
  `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表的角度來看,一個訂單只屬于一個用戶,所以他們是一對一的關系

數(shù)據(jù)庫表的關系

創(chuàng)建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">
  
<!-- 使用接口代理的方式來開發(fā)dao操作數(shù)據(jù)庫,一定要注意,
namespace這里不能再隨便定義,一定要指向我們要執(zhí)行的對應的接口 -->
<mapper namespace="connection.OrdersMapperQueryInterface"> 
</mapper>

創(chuàng)建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">
  
<!-- 使用接口代理的方式來開發(fā)dao操作數(shù)據(jù)庫,一定要注意,
namespace這里不能再隨便定義,一定要指向我們要執(zhí)行的對應的接口 -->
<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>

創(chuàng)建測試類,獲取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();
    }
    
}

一、一對一關聯(lián)查詢

??現(xiàn)在要通過一個訂單的信息及對應的客戶信息,需要使用一對一查詢。實現(xiàn)這個查詢,需要將user類的對象加入到orders類中,然后在mapper文件中,設置user類屬性的映射。

創(chuàng)建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來表示我們一對一的關聯(lián)關系
                注意:一定需要JavaType這個屬性,來表明我們關聯(lián)的對象
         -->
        <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);
        }
    }

二、一對多關聯(lián)查詢

??現(xiàn)在我們要查詢每個用戶對應的訂單情況,一個用戶可以有多個訂單,所以是一對多關聯(lián)查詢。

在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來進行表示 
            在我們一對多的關聯(lián)查詢的時候,一定要使用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);
        }
        
    }
    }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容