第七章 Mybatis多表操作之一对一配置

目录

一、引言

​二、完整代码实现(1)

2.1. 订单实体类 

2.2. 用户实体类 

2.3. OrderMapper.xml 

2.4. sqlMapConfig.xml 

2.5. properties 

2.6. OrderMapper 

2.7. UserService 

三、代码实现(2)


一、引言

在我们日常开发中,经常会碰到多表连接查询的业务场景,比如查询某一笔订单(包含所属用户信息),这种我们称之为一对一查询。在MyBatis中,一对一查询通常是通过配置映射文件中的<resultMap>来实现的。

一对一查询模型

用户表和订单表的关系为:

1. 一个用户有多个订单,一个订单只从属于一个用户,订单表uid关联用户表id。

2. 一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户。

二、完整代码实现(1)

2.1. 订单实体类 

package com.example.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
    private int id;
    private Date orderTime;
    private double total;
    // 代表当前订单从属于哪一个用户
    private User user;
}

2.2. 用户实体类 

package com.example.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
}

2.3. OrderMapper.xml 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.OrderMapper">

    <resultMap id="orderMap" type="com.example.domain.Order">
        <!-- 手动指定字段与实体属性的映射关系
            column: 数据表的字段名称
            property: 实体的属性名称
         -->
        <id column="oid" property="id"></id>
        <result column="ordertime" property="orderTime"></result>
        <result column="total" property="total"></result>
        <result column="uid" property="user.id"></result>
        <result column="username" property="user.username"></result>
        <result column="password" property="user.password"></result>
        <result column="birthday" property="user.birthday"></result>
    </resultMap>

    <!-- 查询操作 -->
    <select id="findAll" resultMap="orderMap">
        select *, o.id oid from `order` o inner join USER u on o.uid=u.id
    </select>
</mapper>

2.4. sqlMapConfig.xml 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 加载外部properties -->
    <properties resource="jdbc.properties"></properties>

    <settings>
        <!-- 其他配置 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <typeAlias type="com.example.domain.User" alias="user"></typeAlias>
    </typeAliases>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 指定方言 MySQl -->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>
    
    <!-- 数据源环境 -->
    <environments default="development">
        <environment id="development">
            <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>
        <mapper resource="com/example/mapper/UserMapper.xml"/>
        <mapper resource="com/example/mapper/OrderMapper.xml"/>
    </mappers>
</configuration>

2.5. properties 

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=Wangzhexiao

2.6. OrderMapper 

package com.example.mapper;

import com.example.domain.Order;
import java.io.IOException;
import java.util.List;

public interface OrderMapper {

    List<Order> findAll() throws IOException;
}

2.7. UserService 

package com.example.service;

import com.example.domain.Order;
import com.example.mapper.OrderMapper;
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;
import java.util.List;

public class UserService {
    public static void main(String[] args) throws IOException {
        // 获得核心配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        // 获得Session工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 获得Session会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 获取Dao代理对象,Mybatis内部已经帮我们完成了实现(与我们传统方式代码中的实现类相似)
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        List<Order> list = mapper.findAll();
        for (Order order : list) {
            System.out.println(order);
        }
    }
}

三、代码实现(2)

我们在上个代码的基础上做适当调整:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.OrderMapper">

    <resultMap id="orderMap" type="com.example.domain.Order">
        <!-- 手动指定字段与实体属性的映射关系
            column: 数据表的字段名称
            property: 实体的属性名称
         -->
        <id column="oid" property="id"></id>
        <result column="ordertime" property="orderTime"></result>
        <result column="total" property="total"></result>
<!--        <result column="uid" property="user.id"></result>-->
<!--        <result column="username" property="user.username"></result>-->
<!--        <result column="password" property="user.password"></result>-->
<!--        <result column="birthday" property="user.birthday"></result>-->
        <association property="user" javaType="user">
            <result column="uid" property="id"></result>
            <result column="username" property="username"></result>
            <result column="password" property="password"></result>
            <result column="birthday" property="birthday"></result>
        </association>
    </resultMap>

    <!-- 查询操作 -->
    <select id="findAll" resultMap="orderMap">
        select *, o.id oid from `order` o inner join USER u on o.uid=u.id
    </select>
</mapper>

上一篇:深入理解JAVA虚拟机(一)


下一篇:自适应阻抗控制基本概念