Mybatis实现订单案例的五表联合操作

Mybatis实现订单案例的五表联合操作
上一个笔记中已经完成了五表的设计,本案例使用mybatis来完成相应的查询功能
pom文件添加junit,mysql, mybatis(3.4.4)

设置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>

<!--
    引入db的配置文件信息,后面用到的四个连接字符串就可以直接使用 ${}的方式来动态引入
-->
<properties resource="db.properties" />

<!--
    给当前mybatis项目添加日志功能,该STDOUT_LOGGING值的好处是不用添加第三方jar包就可以有日志的输出
-->
<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${user}"/>
            <property name="password" value="${pass}"/>
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource="com/qfedu/mapper/OrderMapper.xml"/>
    <mapper resource="com/qfedu/mapper/UserMapper.xml"/>
    <mapper resource="com/qfedu/mapper/DetailMapper.xml"/>
    <mapper resource="com/qfedu/mapper/ProductMapper.xml"/>
    <mapper resource="com/qfedu/mapper/TypeMapper.xml"/>
</mappers>

</configuration>

db.properties数据库的配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mall
user=root
pass=123456

设计pojo类

User.java

package com.qfedu.pojo;

public class User {
private int uid;
private String name;
private String pass;
private String phone;

@Override
public String toString() {
    return "User{" +
            "uid=" + uid +
            ", name='" + name + '\'' +
            ", pass='" + pass + '\'' +
            ", phone='" + phone + '\'' +
            '}';
}

public int getUid() {
    return uid;
}

public void setUid(int uid) {
    this.uid = uid;
}

public String getName() {
    return name;
}

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

public String getPass() {
    return pass;
}

public void setPass(String pass) {
    this.pass = pass;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

}

Type.java

package com.qfedu.pojo;

public class Types {

private String tid;
private String name;

@Override
public String toString() {
    return "Types{" +
            "tid=" + tid +
            ", name='" + name + '\'' +
            '}';
}

public String getTid() {
    return tid;
}

public void setTid(String tid) {
    this.tid = tid;
}

public String getName() {
    return name;
}

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

}

Product.java

package com.qfedu.pojo;

public class Product {

private String pid;
private String name;
private String img;
private double price;
private Types t;

@Override
public String toString() {
    return "Product{" +
            "pid='" + pid + '\'' +
            ", name='" + name + '\'' +
            ", img='" + img + '\'' +
            ", price=" + price +
            ", t=" + t +
            '}';
}

public String getPid() {
    return pid;
}

public void setPid(String pid) {
    this.pid = pid;
}

public String getName() {
    return name;
}

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

public String getImg() {
    return img;
}

public void setImg(String img) {
    this.img = img;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public Types getT() {
    return t;
}

public void setT(Types t) {
    this.t = t;
}

}

Detail.java

package com.qfedu.pojo;

public class Detail {

private String did;
private int count;
private Product pro;

@Override
public String toString() {
    return "Detail{" +
            "did='" + did + '\'' +
            ", count=" + count +
            ", pro=" + pro +
            '}';
}

public String getDid() {
    return did;
}

public void setDid(String did) {
    this.did = did;
}

public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public Product getPro() {
    return pro;
}

public void setPro(Product pro) {
    this.pro = pro;
}

}

Order.java

package com.qfedu.pojo;

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;

@Override
public String toString() {
    return "Order{" +
            "oid='" + oid + '\'' +
            ", price=" + price +
            ", addr='" + addr + '\'' +
            ", payType='" + payType + '\'' +
            ", u=" + u +
            ", details=" + details +
            '}';
}

public String getOid() {
    return oid;
}

public void setOid(String oid) {
    this.oid = oid;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public String getAddr() {
    return addr;
}

public void setAddr(String addr) {
    this.addr = addr;
}

public String getPayType() {
    return payType;
}

public void setPayType(String payType) {
    this.payType = payType;
}

public User getU() {
    return u;
}

public void setU(User u) {
    this.u = u;
}

public List<Detail> getDetails() {
    return details;
}

public void setDetails(List<Detail> details) {
    this.details = details;
}

}

设置映射文件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.qfedu.pojo.OrderMapper">

<select id="getOrderByOid" resultMap="orderMap">
  select * from orders where oid = #{oid}
</select>

<resultMap id="orderMap" type="com.qfedu.pojo.Order">

    <!--
        id代表主键,分别设置列和属性的对应关系
    -->
    <id property="oid" column="oid" ></id>

    <!--
        result代表普通字段的映射,分别指定列与属性的对应

        如果字段名和属性名一致,可以省略

        属性名叫做payType,字段名pay_type;
        <result column="pay_type" property="payType" />
    -->
    <result column="price" property="price" />
    <result column="addr" property="addr" />
    <result column="payType" property="payType" />

    <!--
        association关联,只要是"对一"的关系都可以使用association,代表关联
        property代表Order类中的属性名u
        column代表Orders表与Users表之间的关联字段
        select代表要使用该查询完成两表的联合查询得出user对象
    -->
    <association property="u" column="uid" select="com.qfedu.pojo.UserMapper.getUserByUid"></association>

    <!--
        collection设置集合,只要是"对多"多关系,都可以使用collection,代表集合
        column代表orders表与details表之间的关联字段
    -->
    <collection property="details" column="oid" select="com.qfedu.pojo.DetailMapper.getDetailsByOid" ofType="com.qfedu.pojo.Detail" />
</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="com.qfedu.pojo.UserMapper">

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

</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.qfedu.pojo.DetailMapper">

<select id="getDetailsByOid" resultMap="detailMap">
  select * from details where oid = #{oid}
</select>

<resultMap id="detailMap" type="com.qfedu.pojo.Detail">
    <id column="did" property="did"></id>

    <result property="count" column="count" />

    <association property="pro" column="pid" select="com.qfedu.pojo.ProductMapper.getProductByPid" />
</resultMap>

</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.qfedu.pojo.ProductMapper">

<select id="getProductByPid" resultMap="productMap">
  select * from products where pid = #{uid}
</select>

<resultMap id="productMap" type="com.qfedu.pojo.Product">
    <id column="pid" property="pid"></id>

    <association property="t" column="tid" select="com.qfedu.pojo.TypeMapper.getTypesByTid" />
</resultMap>

</mapper>

TypeMapper.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.qfedu.pojo.TypeMapper">

<select id="getTypesByTid" resultType="com.qfedu.pojo.Types">
  select * from types where tid = #{tid}
</select>

</mapper>

TestOrder.java

package com.qfedu.test;

import com.qfedu.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 testSession(){
// System.out.println(session);
// }

@Test
public void testGetOrderByOid(){
    Order order = session.selectOne("com.qfedu.pojo.OrderMapper.getOrderByOid", "d44e970b629d11eaad320242ac110003");

    System.out.println(order);
}

}

运行结果

/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/bin/java -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=50351:/Applications/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar:/Applications/IntelliJ IDEA.app/Contents/plugins/junit/lib/junit-rt.jar:/Applications/IntelliJ IDEA.app/Contents/plugins/junit/lib/junit5-rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/tools.jar:/Users/james/Documents/NZ1903/lesson/Days22Mybatis2/target/test-classes:/Users/james/Documents/NZ1903/lesson/Days22Mybatis2/target/classes:/Users/james/Documents/doc/repository/junit/junit/4.12/junit-4.12.jar:/Users/james/Documents/doc/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar:/Users/james/Documents/doc/repository/mysql/mysql-connector-java/5.1.44/mysql-connector-java-5.1.44.jar:/Users/james/Documents/doc/repository/org/mybatis/mybatis/3.4.4/mybatis-3.4.4.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.qfedu.test.TestOrders,testGetOrderByOid
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Opening JDBC Connection
Wed Mar 11 11:34:57 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@79efed2d]
==> Preparing: select * from orders where oid = ?
==> Parameters: d44e970b629d11eaad320242ac110003(String)
<== Columns: oid, price, addr, payType, uid
<== Row: d44e970b629d11eaad320242ac110003, 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: d44e970b629d11eaad320242ac110003(String)
<==== Columns: did, count, pid, oid
<==== Row: 35984c20629e11eaad320242ac110003, 2, 321607c2629b11eaad320242ac110003, d44e970b629d11eaad320242ac110003
======> Preparing: select * from products where pid = ?
======> Parameters: 321607c2629b11eaad320242ac110003(String)
<====== Columns: pid, name, img, price, tid
<====== Row: 321607c2629b11eaad320242ac110003, iphone x, iphone.jpg, 9999, dd6501cb628111eaad320242ac110003
========> Preparing: select * from types where tid = ?
========> Parameters: dd6501cb628111eaad320242ac110003(String)
<======== Columns: tid, name
<======== Row: dd6501cb628111eaad320242ac110003, digit
<======== Total: 1
<====== Total: 1
<==== Row: 569250ff629e11eaad320242ac110003, 1, ba23b88a629b11eaad320242ac110003, d44e970b629d11eaad320242ac110003
======> Preparing: select * from products where pid = ?
======> Parameters: ba23b88a629b11eaad320242ac110003(String)
<====== Columns: pid, name, img, price, tid
<====== Row: ba23b88a629b11eaad320242ac110003, yagao, heiren.jpg, 99, dd64fd48628111eaad320242ac110003
========> Preparing: select * from types where tid = ?
========> Parameters: dd64fd48628111eaad320242ac110003(String)
<======== Columns: tid, name
<======== Row: dd64fd48628111eaad320242ac110003, house
<======== Total: 1
<====== Total: 1
<==== Row: 56f00543629e11eaad320242ac110003, 1, f07de571628211eaad320242ac110003, d44e970b629d11eaad320242ac110003
======> Preparing: select * from products where pid = ?
======> Parameters: f07de571628211eaad320242ac110003(String)
<====== Columns: pid, name, img, price, tid
<====== Row: f07de571628211eaad320242ac110003, mac pro, mac.jpg, 21999, dd6501cb628111eaad320242ac110003
<====== Total: 1
<==== Total: 3
<== Total: 1
Order{oid='d44e970b629d11eaad320242ac110003', price=30998.0, addr='beijingxisanqi', payType='zhibubao', u=User{uid=1, name='wukong', pass='888888', phone='13333333333'}, details=[Detail{did='35984c20629e11eaad320242ac110003', count=2, pro=Product{pid='321607c2629b11eaad320242ac110003', name='iphone x', img='iphone.jpg', price=9999.0, t=Types{tid=dd6501cb628111eaad320242ac110003, name='digit'}}}, Detail{did='569250ff629e11eaad320242ac110003', count=1, pro=Product{pid='ba23b88a629b11eaad320242ac110003', name='yagao', img='heiren.jpg', price=99.0, t=Types{tid=dd64fd48628111eaad320242ac110003, name='house'}}}, Detail{did='56f00543629e11eaad320242ac110003', count=1, pro=Product{pid='f07de571628211eaad320242ac110003', name='mac pro', img='mac.jpg', price=21999.0, t=Types{tid=dd6501cb628111eaad320242ac110003, name='digit'}}}]}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@79efed2d]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@79efed2d]

Process finished with exit code 0

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

推荐阅读更多精彩内容