基于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.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容