本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

MyBatis(6)之关联查询

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:


准备

# jdbc.properties
jdbc.url=jdbc:mysql://192.168.208.192:3306/test?characterEncoding=utf-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
# log4j.properties
log4j.rootLogger = debug,stdout,E

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
<!-- mybatis/SqlMapConfig.xml -->
<?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>
    <!--
    加载属性文件
        先加载内部标签,再加载外部文件,名称一致时,会覆盖内部标签内容
     -->
    <properties resource="jdbc.properties"/>

    <!--别名扫描-->
    <typeAliases>
        <package name="com.zze.mybatis.pojo" />
    </typeAliases>

    <!-- 和 spring 整合后 environments配置将废除-->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理-->
            <transactionManager type="JDBC"/>
            <!-- 数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <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.zze.mybatis.mapper"/>
    </mappers>
</configuration>
// com.zze.mybatis.pojo.User
import java.util.Date;

public class User {
    private Integer id;
    private String name;
    private Date birthday;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
// com.zze.mybatis.util.SqlSessionFactoryUtil
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 SqlSessionFactoryUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        // 创建 SqlSessionFactoryBuilder 对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 创建核心配置文件的输入流
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("mybatis/SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建 Session 工厂
        sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
    }

    /**
     * 打开一个 Session
     *
     * @return SqlSession 实例
     */
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }

    /**
     * 打开一个 Session
     *
     * @param autoCommit 是否自动提交事务
     * @return SqlSession 实例
     */
    public static SqlSession openSession(Boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }
}
<!-- pom.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zze.mybatis</groupId>
    <artifactId>mybatis_test2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.11.0.GA</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

示例

一对一

新建与用户关联的订单表和 POJO,配置映射文件:

// com.zze.mybatis.pojo.Order

import java.util.Date;

public class Order {
    private Integer id;
    private Integer uId;
    private Double totalPrice;
    private Date createDate;
    /*
    Order 一对一关联 User
     */
    private User user;

    public Integer getId() {
        return id;
    }

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

    public Integer getuId() {
        return uId;
    }

    public void setuId(Integer uId) {
        this.uId = uId;
    }

    public Double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", uId=" + uId +
                ", TotalPrice=" + totalPrice +
                ", createDate=" + createDate +
                ", user=" + user +
                '}';
    }
}
<!-- com/zze/mybatis/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.zze.mybatis.mapper.OrderMapper">
    <resultMap id="orderMap" type="order">
        <!--
        注意:
                在关联查询时,每个映射字段都需配置,不可省略。
        -->
        <id property="id" column="oid"/>
        <result property="uId" column="uid"/>
        <result property="totalPrice" column="totalPrice"/>
        <result property="createDate" column="createdate"/>
        <!--
        通过 association 配置一对一关系
        -->
        <association property="user" javaType="user">
            <id property="id" column="uid"/>
            <result property="name" column="name"/>
            <result property="birthday" column="birthday"/>
        </association>
    </resultMap>

    <select id="getAll" resultMap="orderMap">
      select o1.id oid,o1.uid,totalPrice,createdate,name,birthday from `order` o1 left join `user` u1 on o1.uid = u1.id;
    </select>
</mapper>
package com.zze.mybatis.test;

import com.zze.mybatis.mapper.OrderMapper;
import com.zze.mybatis.pojo.Order;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class OrderTest {

    private OrderMapper orderMapper;

    @Before
    public void init() {
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
        orderMapper = sqlSession.getMapper(OrderMapper.class);
    }

    @Test
    public void test() {
        List<Order> orderList = orderMapper.getAll();
        orderList.forEach(o -> System.out.println(o));

        /*
        ==>  Preparing: select o1.id oid,o1.uid,totalPrice,createdate,name,birthday from `order` o1 left join `user` u1 on o1.uid = u1.id;

        Order{id=1, uId=1, TotalPrice=324.0, createDate=Thu Mar 21 11:10:20 CST 2019, user=User{id=1, name='张三', birthday=Thu Jan 01 00:00:00 CST 1998}}
        Order{id=3, uId=1, TotalPrice=543.0, createDate=Mon Mar 18 11:11:05 CST 2019, user=User{id=1, name='张三', birthday=Thu Jan 01 00:00:00 CST 1998}}
        Order{id=2, uId=3, TotalPrice=23.0, createDate=Fri Mar 01 06:04:07 CST 2019, user=User{id=3, name='李四', birthday=Thu Jan 01 00:00:00 CST 1998}}
         */
    }
}

一对多

修改用户的 POJO 关联订单,配置映射文件:

// com.zze.mybatis.pojo.User
import java.util.Date;
import java.util.List;

public class User {
    private Integer id;
    private String name;
    private Date birthday;

    /*
    User 一对多关联 Order
     */
    private List<Order> orders;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public List<Order> getOrders() {
        return orders;
    }

    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
<!-- com/zze/mybatis/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.zze.mybatis.mapper.UserMapper">
    <resultMap id="userMap" type="user">
        <id property="id" column="uId"/>
        <result property="name" column="name"/>
        <result property="birthday" column="birthday"/>
        <!--
        使用 collection 标签建立一对多关系
            注意,这里使用的是 ofType,而一对一关联时使用的是 javaType
        -->
        <collection property="orders" ofType="order">
            <id property="id" column="oId"/>
            <result property="totalPrice" column="totalPrice"/>
            <result property="createDate" column="createDate"/>
            <result property="uId" column="uId"/>
        </collection>
    </resultMap>

    <select id="getAll" resultMap="userMap">
        select u1.id uId,o1.id oId,totalPrice,createdate,name,birthday from `user` u1 left join `order` o1 on u1.id=o1.uid;
    </select>
</mapper>
# MyBatis  

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×