Mybatis表的关联查询

导语:
关于<resultMap>标签映射,<association>&<collection>的使用:跳转文章查看
无论是什么关联关系,如果某方持有另一方的集合,则使用标签完成映射,如果某方持有另一方的对象,则使用标签完成映射。

一对多查询:

根据顾客ID查询顾客信息(一),同时将顾客名下所有订单查出(多)。
实现思路:

  • 创建顾客类,存储顾客信息:
    注意我们在顾客类中用List集合封装了顾客名下的订单信息。
package com.user.pojo;

import java.util.List;

public class Customer {
    //customer表中的三个列
    private Integer id;
    private String name;
    private Integer age;
    //该客户名下所有订单集合
    private List<Order> orderList;

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", orderList=" + orderList +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

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

    public Customer(Integer id, String name, Integer age, List<Order> orderList) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.orderList = orderList;
    }

    public Customer() {
    }
}

  • 创建订单类,存储订单信息:
package com.user.pojo;

public class Order {
    private Integer id;
    private String orderNumber;
    private Double orderPrice;

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", orderNumber='" + orderNumber + '\'' +
                ", orderPrice=" + orderPrice +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }

    public Double getOrderPrice() {
        return orderPrice;
    }

    public void setOrderPrice(Double orderPrice) {
        this.orderPrice = orderPrice;
    }

    public Order(Integer id, String orderNumber, Double orderPrice) {
        this.id = id;
        this.orderNumber = orderNumber;
        this.orderPrice = orderPrice;
    }

    public Order() {
    }
}

  • 动态代理接口:
package com.user.mapper;

import com.user.pojo.Customer;

public interface CustomerMapper {
    //根据客户id查询客户所有信息并同时查询该客户名下的所有订单
    Customer getById(Integer id);
}
  • Mapper.xml文件:
    因为我们的查询结果包括该顾客信息和顾客所有的订单信息,所以我们的返回值需要自定义一个map集合来存储。我们这里使用 标签映射的方式创建我们的集合customermap,并将该集合作为我们的返回值类型。

DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.user.mapper.CustomerMapper">
    
    <resultMap id="customermap" type="customer">
        
        
        <id  property="id" column="id">id>
        
        <result property="name" column="name">result>
        <result property="age" column="age">result>
        
        <collection property="orderList" ofType="order">
            <id property="id" column="id">id>
            <result property="orderNumber" column="orderNumber">result>
            <result property="orderPrice" column="orderPrice">result>
        collection>
    resultMap>
    <select id="getById" parameterType="Integer" resultMap="customermap">
        select customer.id ,name,age ,orders.id ,orderNumber ,orderPrice ,customer_id
        from customer left join orders on customer.id = orders.customer_id
        where customer.id = #{id}
    select>
    
mapper>
  • 测试程序:
import java.io.InputStream;
import java.util.List;

public class MyTest {
    SqlSession sqlSession;
    CustomerMapper customerMapper;
    @Before
    public void openSqlSession() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        sqlSession = factory.openSession();
        customerMapper = sqlSession.getMapper(CustomerMapper.class);
    }
    @After
    public void closeSqlSession(){
        sqlSession.close();
    }
    @Test
    public  void testGetCustomerById(){
        Customer customer = customerMapper.getById(1);
        System.out.println(customer);
    }
}
  • 其余基础配置文件SqlMapConfig.xml:

DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties">properties>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    <typeAliases>
        <package name="com.user.pojo"/>
        <package name="com.user.mapper"/>
    typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>
    <mappers>
        <package name="com.user.mapper">package>
    mappers>
configuration>

Mybatis表的关联查询_第1张图片
Mybatis表的关联查询_第2张图片

多对一查询:

根据订单ID查询订单信息及该订单所属的顾客的信息。
实现思路:

  • 创建订单类,存储订单信息:
    注意我们在订单类中封装了该订单下的顾客的信息。
package com.user.pojo;

public class Order {
    //订单信息
    private Integer id;
    private String orderNumber;
    private Double orderPrice;
    private Integer customer_id;
    //订单所属的客户
    private Customer customer;

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", orderNumber='" + orderNumber + '\'' +
                ", orderPrice=" + orderPrice +
                ", customer_id=" + customer_id +
                ", customer=" + customer +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }

    public Double getOrderPrice() {
        return orderPrice;
    }

    public void setOrderPrice(Double orderPrice) {
        this.orderPrice = orderPrice;
    }

    public Integer getCustomer_id() {
        return customer_id;
    }

    public void setCustomer_id(Integer customer_id) {
        this.customer_id = customer_id;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Order(Integer id, String orderNumber, Double orderPrice, Integer customer_id, Customer customer) {
        this.id = id;
        this.orderNumber = orderNumber;
        this.orderPrice = orderPrice;
        this.customer_id = customer_id;
        this.customer = customer;
    }

    public Order() {
    }
}


  • 创建顾客类,存储顾客信息:
package com.user.pojo;

import java.util.List;

public class Customer {
    //顾客信息
    private Integer id;
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Customer(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Customer() {
    }
}

  • 动态代理接口:
    package com.user.mapper;

    import com.user.pojo.Customer;
    import com.user.pojo.Order;

    public interface OrderMapper {
        //根据主键查订单并同时查询该订单的客户信息
        Order getById(Integer id);
    }

  • Mapper.xml文件:
    因为我们的查询结果包括该订单信息和订单所属顾客的信息,所以我们的返回值需要自定义一个map集合来存储。我们这里使用 标签映射的方式创建我们的集合customermap,并将该集合作为我们的返回值类型。

DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.user.mapper.OrderMapper">
    
    <resultMap id="ordermap" type="order">
        
        
        <id  property="id" column="id">id>
        
        <result property="orderNumber" column="orderNumber">result>
        <result property="orderPrice" column="orderPrice">result>
        <result property="customer_id" column="customer_id">result>
        
        <association property="customer" javaType="customer">
            <id property="id" column="id">id>
            <result property="name" column="name">result>
            <result property="age" column="age">result>
        association>
    resultMap>
    <select id="getById" parameterType="Integer" resultMap="ordermap">
        select orders.id ,orderNumber ,orderPrice ,customer_id ,customer.id ,name,age
        from orders left join customer on orders.customer_id = customer.id
        where orders.id = #{id}
    select>
mapper>
  • 测试类:
package com.user;

import com.user.mapper.OrderMapper;
import com.user.pojo.Order;
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.After;
import org.junit.Before;
import org.junit.Test;

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

public class MyTest {
    SqlSession sqlSession;
    OrderMapper orderMapper;
    @Before
    public void openSqlSession() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        sqlSession = factory.openSession();
        orderMapper = sqlSession.getMapper(OrderMapper.class);
    }
    @After
    public void closeSqlSession(){
        sqlSession.close();
    }
    @Test
    public void testGetOrderById(){
        Order order = orderMapper.getById(11);
        System.out.println(order);
    }
}

  • 其余基础配置文件:

DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties">properties>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    <typeAliases>
        <package name="com.user.pojo"/>
        <package name="com.user.mapper"/>
    typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>
    <mappers>
        <package name="com.user.mapper">package>
    mappers>
configuration>

Mybatis表的关联查询_第3张图片

Mybatis表的关联查询_第4张图片

一对一查询:

同多对一。

  • 实体类:
    在这里插入图片描述
  • 动态代理接口:
    在这里插入图片描述
  • mapper.xml文件:
    Mybatis表的关联查询_第5张图片

多对多查询:

多对多关联中,需要通过中间表化解关联关系。中间表描述两张主键表的关联。

你可能感兴趣的:(MyBatis,java,mybatis,spring)