基于MyBatis的多表联合查询表数据

1.下面是我的idea的目录结构:

mybatis01.jpg

2.下面是com.it.pojo的代码:

package com.it.pojo;

public class User {
    private int uid;
    private String name;
    private String pass;
    private String phone;
    //setter和getter,toString省略   
}
public class Types {
    private String tid;
    private String name;
   //setter和getter,toString省略   
}
public class Product {
    private String pid;
    private String name;
    private String img;
    private double price;
    private Types t;
   //setter和getter,toString省略   
}
public class Detail {
    private String did;
    private int count;
    private Product p;
   //setter和getter,toString省略   
}
import java.util.List;

public class Order {
    private String oid;
    private double price;
    private String addr;
    private String payType;
    private User u;
    private List<Detail> Details;
   //setter和getter,toString省略   
}

3.下面是mybatis的核心文件配置

<?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>
    <settings>
        <setting name="cacheEnabled" value="true" />
        <setting name="useGeneratedKeys" value="true" />
        <setting name="defaultExecutorType" value="REUSE" />
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
    <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://127.0.0.1:3306/mall"/>
                <property name="username" value="root"/>
                <property name="password" value="tiger"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com.it.mapper/OrderMapper.xml"/>
        <mapper resource="com.it.mapper/UserMapper.xml"/>
        <mapper resource="com.it.mapper/DetailMapper.xml"/>
        <mapper resource="com.it.mapper/ProductMapper.xml"/>
        <mapper resource="com.it.mapper/TypesMapper.xml"/>
    </mappers>
</configuration>

4.下面是各个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="com.it.pojo.UserMapper">

    <select id="selectUser" resultType="com.it.pojo.User">
        select * from users where uid=#{uid};
    </select>

</mapper>

下面是TypesMapper.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="com.it.pojo.TypesMapper">

    <select id="selectTypesByID" resultType="com.it.pojo.Types">
        select * from types where tid=#{tid};
    </select>
</mapper>

下面是ProductMapper.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="com.it.pojo.ProductMapper">

    <select id="selectProductById" resultMap="productMap">
        select * from products where pid=#{pid};
    </select>
    <resultMap id="productMap" type="com.it.pojo.Product">
        <id column="pid" property="pid"></id>
        <result property="name" column="name"></result>
        <result column="img" property="img"></result>
        <result column="price" property="price"></result>
        <association property="t" column="tid" select="com.it.pojo.TypesMapper.selectTypesByID"></association>
    </resultMap>
</mapper>

下面是DetailMapper.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="com.it.pojo.DetailMapper">

    <select id="getDetailsByOid" resultMap="detailMap">
        select * from details where oid=#{oid};
    </select>
    <resultMap id="detailMap" type="com.it.pojo.Detail">
        <id column="did" property="did"></id>
        <result property="count" column="count"></result>
        <association property="p" column="pid" select="com.it.pojo.ProductMapper.selectProductById"></association>
    </resultMap>
</mapper>

下面是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="com.it.pojo.OrderMapper">

    <select id="getOrderById" resultMap="orderMap">
        select * from orders where oid=#{oid};
    </select>
    <resultMap id="orderMap" type="com.it.pojo.Order">
        <id property="oid" column="oid"></id>
        <result property="price" column="price"></result>
        <result property="addr" column="addr"></result>
        <result property="payType" column="payType"></result>
        <!--
            association关联,只要是"对一"的关系都可以使用association,代表关联
            property代表Order类中的属性名u
            column代表Orders表与Users表之间的关联字段
            select代表要使用该查询完成两表的联合查询得出user对象
        -->
        <association property="u" column="uid" select="com.it.pojo.UserMapper.selectUser"></association>
        <collection property="Details" column="oid" select="com.it.pojo.DetailMapper.getDetailsByOid"></collection>
    </resultMap>
</mapper>

5.下面是测试代码以及测试结果展示

import com.it.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;

public class TestOrders {
    private SqlSessionFactory sf = null;
    private SqlSession session = null;

    @Before
    public void setUp(){
        try {
            sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));

            session = sf.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void tearDown(){
        if(session != null){
            session.close();
            session = null;
        }
    }

    @Test
    public void testGetOrderByOid(){
        Order order = session.selectOne("com.it.pojo.OrderMapper.getOrderById", "7891834e633011eab732005056c00001");
        System.out.println(order);
    }
}

下面是测试结果展示:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1684890795.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@646d64ab]
==>  Preparing: select * from orders where oid=?; 
==> Parameters: 7891834e633011eab732005056c00001(String)
<==    Columns: oid, price, addr, payType, uid
<==        Row: 7891834e633011eab732005056c00001, 30998, beijingxisanqi, zhibubao, 1
====>  Preparing: select * from users where uid=?; 
====> Parameters: 1(Integer)
<====    Columns: uid, name, pass, phone
<====        Row: 1, wukong, 888888, 13333333333
<====      Total: 1
====>  Preparing: select * from details where oid=?; 
====> Parameters: 7891834e633011eab732005056c00001(String)
<====    Columns: did, count, pid, oid
<====        Row: 61f4c1d3633211eab732005056c00001, 1, b8591f77633111eab732005056c00001, 7891834e633011eab732005056c00001
======>  Preparing: select * from products where pid=?; 
======> Parameters: b8591f77633111eab732005056c00001(String)
<======    Columns: pid, name, img, price, tid
<======        Row: b8591f77633111eab732005056c00001, mac.pro, mac.jpg, 21999, 007ca8fb632f11eab732005056c00001
========>  Preparing: select * from types where tid=?; 
========> Parameters: 007ca8fb632f11eab732005056c00001(String)
<========    Columns: tid, name
<========        Row: 007ca8fb632f11eab732005056c00001, digit
<========      Total: 1
<======      Total: 1
<====        Row: 61f4c3b1633211eab732005056c00001, 1, b8592172633111eab732005056c00001, 7891834e633011eab732005056c00001
======> Parameters: b8592172633111eab732005056c00001(String)
<======    Columns: pid, name, img, price, tid
<======        Row: b8592172633111eab732005056c00001, iphone, iphone.jpg, 9999, 007ca8fb632f11eab732005056c00001
<======      Total: 1
<====        Row: 61f4c400633211eab732005056c00001, 1, b85921bc633111eab732005056c00001, 7891834e633011eab732005056c00001
======> Parameters: b85921bc633111eab732005056c00001(String)
<======    Columns: pid, name, img, price, tid
<======        Row: b85921bc633111eab732005056c00001, yagao, yagao.jpg, 50, 007ca7cd632f11eab732005056c00001
========> Parameters: 007ca7cd632f11eab732005056c00001(String)
<========    Columns: tid, name
<========        Row: 007ca7cd632f11eab732005056c00001, house
<========      Total: 1
<======      Total: 1
<====      Total: 3
<==      Total: 1
Order{oid='7891834e633011eab732005056c00001', price=30998.0, addr='beijingxisanqi', payType='zhibubao', u=user{uid=1, name='wukong', pass='888888', phone='13333333333'}, Details=[Detail{did='61f4c1d3633211eab732005056c00001', count=1, p=Product{pid='b8591f77633111eab732005056c00001', name='mac.pro', img='mac.jpg', price=21999.0, t=Types{tid='007ca8fb632f11eab732005056c00001', name='digit'}}}, Detail{did='61f4c3b1633211eab732005056c00001', count=1, p=Product{pid='b8592172633111eab732005056c00001', name='iphone', img='iphone.jpg', price=9999.0, t=Types{tid='007ca8fb632f11eab732005056c00001', name='digit'}}}, Detail{did='61f4c400633211eab732005056c00001', count=1, p=Product{pid='b85921bc633111eab732005056c00001', name='yagao', img='yagao.jpg', price=50.0, t=Types{tid='007ca7cd632f11eab732005056c00001', name='house'}}}]}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@646d64ab]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@646d64ab]
Returned connection 1684890795 to pool.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容