MyBatis 关联查询的实现:一对多

2020-01-08 16:03:26来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

MyBatis 关联查询的实现:一对多

有2个实体:用户、订单,一个用户可以拥有多个订单,同时这多个订单属于一个用户,即一对多。

 

user_tb:

 

 

order_tb:

在“多”的一方(order)添加“一”的一方(user)的主键(user_id)作为外键。

 

 


 

 

使用嵌套结果实现一对多

(1)给2个实体都编写pojo类,需要在“一”的一方写个List来关联“多”的一方

package com.chy.pojo;

public class Order {
    private Integer no;
    private Integer goods_id;
    private Integer goods_amount;

    public Integer getNo() {
        return no;
    }

    public void setNo(Integer no) {
        this.no = no;
    }

    public Integer getGoods_id() {
        return goods_id;
    }

    public void setGoods_id(Integer goods_id) {
        this.goods_id = goods_id;
    }

    public Integer getGoods_amount() {
        return goods_amount;
    }

    public void setGoods_amount(Integer goods_amount) {
        this.goods_amount = goods_amount;
    }

    @Override
    public String toString() {
        return "Order{" +
                "no=" + no +
                ", goods_id=" + goods_id +
                ", goods_amount=" + goods_amount +
                '}';
    }
}

 

 

package com.chy.pojo;

import java.util.List;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String tel;
    private String address;
    private List<Order> orderList;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getAddress() {
        return address;
    }

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

    public List<Order> getOrderList() {
        return orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", tel='" + tel + '\'' +
                ", address='" + address + '\'' +
                ", orderList=" + orderList +
                '}';
    }
}

toString()只是为了方便测试、调试,后期可以去掉。

 

 

(2)给“一”的一方写Mapper接口、xml映射文件

package com.chy.mapper;

import com.chy.pojo.User;

public interface UserMapper {
    public User queryUserById(Integer id);
}

 

<?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.chy.mapper.UserMapper">
    <select id="queryUserById" parameterType="integer" resultMap="userResultWithOrder">
        SELECT user_tb.*,order_tb.* FROM user_tb,order_tb WHERE user_tb.id=#{id} AND order_tb.user_id=user_tb.id
     </select>
    <resultMap id="userResultWithOrder" type="user">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="password" column="password"/>
        <result property="tel" column="tel"/>
        <result property="address" column="address"/>
        <collection property="orderList" ofType="order">
            <id property="no" column="no"/>
            <result property="goods_id" column="goods_id" />
            <result property="goods_amount" column="goods_amount" />
        </collection>
    </resultMap>
</mapper>

因为关联的是集合(List),所以用<collection>,property指定表示多的一方(list)的属性名,ofType指定多的一方的数据类型(pojo类),注意不是list。

<collection>里用<id>、<result>配置多的一方的映射。

 

所谓关联查询,是查询结果中同时包含双方(2张表)的多个字段,

如果只查询一张表的字段,比如说只查询某个用户的订单,不查询此用户本身的信息,直接根据外键user_id查order_tb表,不需要查user_tb,不必使用关联查询,写个OrderMapper接口、OrderMapper.xml就ok。

 

 

(3)使用

package com.chy.utils;

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 java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

 

package com.chy.test;

import com.chy.mapper.UserMapper;
import com.chy.pojo.User;
import com.chy.utils.MyBatisUtils;
import org.apache.ibatis.session.*;

public class Test {
    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
}

 

也可以使用嵌套查询来实现一对多(不推荐)。


原文链接:https://www.cnblogs.com/chy18883701161/p/12166505.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:JVM探秘:jinfo查看JVM运行时参数

下一篇:springboot (2.0以上)连接mysql配置