1. 程式人生 > >使用Mybatis進行多表聯查操作

使用Mybatis進行多表聯查操作

tail into style 分享圖片 ces oci getname .get 其他

(1)增加一個測試數據庫shop_order,sql語句如下:

CREATE DATABASE `shop_order`;

USE `shop_order`;

CREATE TABLE `t_user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(20) DEFAULT NULL,
  `password` VARCHAR(50) DEFAULT NULL,
  `sex` VARCHAR(2) DEFAULT NULL,
  `brithday` DATE DEFAULT NULL,
  `address` 
VARCHAR(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8; CREATE TABLE `t_product` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(100) DEFAULT NULL, `price` FLOAT DEFAULT NULL, `description` TEXT, PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=
10 DEFAULT CHARSET=utf8; CREATE TABLE `t_order` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `userId` INT(11) DEFAULT NULL, `createTime` DATETIME DEFAULT NULL, `state` VARCHAR(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_userId` (`userId`), CONSTRAINT `fk_userId` FOREIGN KEY (`userId`) REFERENCES
`t_user` (`id`) ) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `t_orderdetail` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `productId` INT(11) DEFAULT NULL, `orderId` INT(11) DEFAULT NULL, `num` INT(11) DEFAULT NULL, `price` FLOAT DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_productId` (`productId`), KEY `fk_orderId` (`orderId`), CONSTRAINT `fk_orderId` FOREIGN KEY (`orderId`) REFERENCES `t_order` (`id`), CONSTRAINT `fk_productId` FOREIGN KEY (`productId`) REFERENCES `t_product` (`id`) ) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; INSERT INTO `t_user`(`id`,`username`,`password`,`sex`,`brithday`,`address`) VALUES (16,小黃,2222,,2014-01-01,中國),(17,陌拜,1100,,2014-03-03,深圳),(18,本拉登,9999,,2003-09-09,印度),(19,奧巴馬小號,1399,,2005-01-09,美國); INSERT INTO `t_product`(`id`,`name`,`price`,`description`) VALUES (6,飛機,20000000,預售,提貨時間暫定),(7,坦克,300000000,預售,提貨時間暫定),(8,大炮,500000,預售,提貨時間暫定),(9,航母,900000000,預售,提貨時間暫定); INSERT INTO `t_order`(`id`,`userId`,`createTime`,`state`) VALUES (1,18,2015-07-04 00:00:00,已付),(2,19,2017-01-02 00:00:00,已付),(3,16,2017-12-13 10:07:21,待付),(4,18,2017-12-05 14:44:04,報廢); INSERT INTO `t_orderdetail`(`id`,`productId`,`orderId`,`num`,`price`) VALUES (1,8,1,6,3000000),(2,9,2,1,900000000),(3,6,NULL,NULL,NULL);

技術分享圖片

(2)建立程序的結構,結構如下

技術分享圖片

(3)建立實體類,與數據庫中的表對應

Order.java代碼如下:

package entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class Order {
    private int id;
    private Date userId;
    private String createTime;
    private String state;
  //註意這裏報錯是正常的,因為這裏之後引用了其他的實體類,它們還沒被定義,把所有的實體類建立好了以後,保存一下就可以了
private User user; //一個訂單對應一個用戶,所以在訂單中放置一個User的對象 //一個訂單可以有多件商品,這裏對應多個商品詳情,所以放置一個商品詳情集合 private List<OrderDetail> orderDetails = new ArrayList<OrderDetail>(); public Order() { super(); } public Order(int id, Date userId, String createTime, String state) { super(); this.id = id; this.userId = userId; this.createTime = createTime; this.state = state; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getUserId() { return userId; } public void setUserId(Date userId) { this.userId = userId; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getState() { return state; } public void setState(String state) { this.state = state; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<OrderDetail> getOrderDetails() { return orderDetails; } public void setOrderDetails(List<OrderDetail> orderDetails) { this.orderDetails = orderDetails; } }

OrderDetail.java類的代碼如下:

package entity;

public class OrderDetail {
    private int id;
    private int productId;
    private int orderId;
    private double price;
    private int num;
    private Order order;   //一個訂單詳情,對應某一個訂單,所有在這裏添加一個訂單對象
    private Product product;    //一個訂單詳情裏面存放一種商品,對應一個商品詳情
    public OrderDetail() {
        super();
    }
    public OrderDetail(int id, int productId, int orderId, double price, int num) {
        super();
        this.id = id;
        this.productId = productId;
        this.orderId = orderId;
        this.price = price;
        this.num = num;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public Order getOrder() {
        return order;
    }
    public void setOrder(Order order) {
        this.order = order;
    }
    public int getProductId() {
        return productId;
    }
    public void setProductId(int productId) {
        this.productId = productId;
    }
    public int getOrderId() {
        return orderId;
    }
    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }
    public Product getProduct() {
        return product;
    }
    public void setProduct(Product product) {
        this.product = product;
    }
}

Product.java類代碼

package entity;

public class Product {
    private int id;
    private String name;
    private float price;
    private String description;
    public Product() {
        super();
    }
    public Product(int id, String name, float price, String description) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.description = description;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

User.java類的代碼如下:

package entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class User {
    private int id;
    private String username;
    private String password;
    private String sex;
    private Date brithday;
    private String address;
    private List<Order> orders = new ArrayList<Order>();
    public User() {
        super();
    }
    public User(int id, String username, String password, String sex,
            Date brithday, String address) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.brithday = brithday;
        this.address = address;
    }
    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 getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBrithday() {
        return brithday;
    }
    public void setBrithday(Date brithday) {
        this.brithday = brithday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public List<Order> getOrders() {
        return orders;
    }
    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }
}

(4)編寫mybatis-config.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>        
    <!-- 環境:配置mybatis的環境  -->
    <environments default="development">    <!-- 可以使用多個環境變量,切換時只需修改對應default的屬性為該環境變量的id即可  -->
        <!-- 環境變量:可以配置多個環境變量,比如使用多數據源時,就需要配置多個環境變量 -->
        <environment id="development">
            <!-- 事務管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 數據源 -->
            <dataSource type="POOLED">
                <property name="username" value="root" />
                <property name="url" value="jdbc:mysql://localhost:3306/shop_order" />
                <property name="password" value="123" />
                    <!-- 定義驅動連接,根據所使用的數據庫的不同進行更換,作者使用的是mySql -->
                <property name="driver" value="com.mysql.jdbc.Driver" />
            </dataSource>
        </environment>
    </environments>    
</configuration>

(5)編寫SqlSessionUtil.java拿到數據庫的操作對象SqlSession,代碼如下

package common;

import java.io.IOException;
import java.io.InputStream;

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

public class SqlSessionUtil {
    public static SqlSession getSession(){
        InputStream input = null;
        try {
            input = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory=builder.build(input);
        SqlSession session=sqlSessionFactory.openSession();
        return session;
    }
}

(6)編寫dao裏面的接口,這邊學習就只寫了兩個,裏面的方法也很簡單

OrderDao.java

package dao;

import java.util.List;

import entity.Order;

public interface OrderDao {

    /**
     * 查詢所有的訂單,並取出該訂單的用戶信息
     * @return
     */
    List<Order> queryAllOrder();
}

UserDao.java

package dao;

import java.util.List;

import entity.User;

public interface UserDao {
    
    /**
     * 查詢所有用戶,並顯示每個用戶的訂單
     * @return
     */
    List<User> queryAllUser();
}

(7)編寫mapper裏面的xml文件,裏面存放數據庫語句

OrderMapper.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="dao.OrderDao">
  
      <select id="queryAllOrder" resultMap="Order_User">
          select *,od.id as o_id,us.id as u_id from t_order as od inner join t_user as us on od.userId=us.id 
      </select>
      
      <resultMap type="entity.Order" id="Order_User">
          <id column="o_id" property="id"/>
          <result column="userId" property="userId"/>
          <result column="createTime" property="createTime"/>
          <result column="state" property="state"/>
          <association property="user" javaType="entity.User">
          <id column="u_id" property="id"></id>
          <result column="username" property="username"/>
          <result column="password" property="password"/>
          <result column="sex" property="sex"/>
          <result column="brithday" property="brithday"/>
          <result column="address" property="address"/>
          </association>
      </resultMap>        
  </mapper>

UserMapper.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="dao.UserDao">
      <resultMap type="entity.User" id="User_Order">
          <id column="id" property="id"/>
          <result column="username" property="username"/>
          <result column="password" property="password"/>
          <result column="sex" property="sex"/>
          <result column="brithday" property="brithday"/>
          <result column="address" property="address"/>
          
          <collection property="orders" ofType="entity.Order">
              <id column="o_id" property="id"/>
              <result column="userId" property="userId"/>
              <result column="createTime" property="createTime"/>
              <result column="state" property="state"/>
          </collection>
      </resultMap>
  
      <select id="queryAllUser" resultMap="User_Order">
          SELECT *,o.id AS o_id FROM t_user AS u INNER JOIN t_order AS o ON u.id=o.userId
      </select>
  </mapper>

(8)在mybatis-config.xml中的<configuration>標簽裏面<environments>標簽下面添加如下映射

<mappers>
        <mapper resource="mapper/UserMapper.xml"/><!-- 包名。xml文件名 -->
        <!-- <mapper resource="mapper/OrderMapper.xml"></mapper> -->
    </mappers>

(9)編寫方法測試

test.java

package text;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import common.SqlSessionUtil;
import dao.OrderDao;
import dao.UserDao;
import entity.Order;
import entity.User;

public class test {
    
    public static void main(String[] args) {
        SqlSession session = SqlSessionUtil.getSession();//獲取數據庫操作對象SqlSession
        UserDao userDao = session.getMapper(dao.UserDao.class);
        List<User> users = userDao.queryAllUser();
        for (User user : users) {
            System.out.println("用戶:"+user.getUsername()+"的訂單");
            for (Order order : user.getOrders()) {
                System.out.println("訂單編號:"+order.getId());
                System.out.println("狀態:"+order.getState());
            }
            System.out.println();
        }
        
        
        System.out.println("///////////////////////////////////");
        System.out.println();
        OrderDao orderdao = session.getMapper(dao.OrderDao.class);
        List<Order> orders = orderdao.queryAllOrder();
        for (Order order : orders) {
            System.out.println("訂單編號:"+order.getId());
            System.out.println("購買者:"+order.getUser().getUsername());
            System.out.println("訂單狀態:"+order.getState());
            System.out.println();
        }
    }
}

使用Mybatis進行多表聯查操作