Java教程

MyBatis多表操作

本文主要是介绍MyBatis多表操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一对一查询

用户表和订单表的关系为,一个用户多个订单,一个订单只从属一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
在这里插入图片描述
在只查询order表的时候,也要查询user表,所以需要将所有数据全部查出进行封装SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id
在这里插入图片描述

创建Order和User实体

order

public class Order {
    private int id;
    private Date ordertime;
    private double total;
    //表示当前订单属于哪一个用户
    private User user;

user

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;

创建OrderMapper接口

public interface UserMapper {
//查询全部的方法
    public List<Order> findAll();
}

配置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.zg.mapper.OrderMapper" >

    <resultMap id="orderMap" type="order">
        <!--手动指定字段与实体的映射关系-->
        <!--comlumn:数据表的字段名称 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>

    <!--这里不能使用resultType=“order”,因为order中没有user中的字段,只有一个user对象-->
    <select id="findAll" resultMap="orderMap">
        SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id
    </select>

</mapper>


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">
<!--主要配置mybatis的核心配置-->
<configuration>
    <!--通过properties标签加载外部properties文件-->
    <properties resource="jdbc.properties"></properties>
    <!--自定义别名-->
    <typeAliases>
        <typeAlias type="com.zg.domain.User" alias="user"></typeAlias>
        <typeAlias type="com.zg.domain.Order" alias="order"></typeAlias>
    </typeAliases>

    <!--配置当前数据源的环境-->
    <environments default="developement">
        <environment id="developement">
            <transactionManager type="JDBC"></transactionManager>
            <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.zg.mapper/UserMapper.xml"></mapper>
        <mapper resource="com.zg.mapper/OrderMapper.xml"></mapper>
    </mappers>


</configuration>

在这里插入图片描述
在一对一配置的时候,在order实体中创建了一个user,所以property属性都使用user.** 的方式进行编写,但是这里还可以使用association

<?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.zg.mapper.OrderMapper" >

    <resultMap id="orderMap" type="order">
        <!--手动指定字段与实体的映射关系-->
        <!--comlumn:数据表的字段名称 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>-->
        <!--以上被封装到user内的还可以使用association进行配置-->
        <!--association匹配的意思,在order中有个属性叫user-->
        <!-- property="user"当前order实体中的属性名称,javaType="user"当前实体order中的属性类型user-->
        <association property="user" javaType="user">
            <id column="uid" property="id"></id>
            <result column="username" property="username"></result>
            <result column="password" property="password"></result>
            <result column="birthday" property="birthday"></result>
        </association>
        

    </resultMap>

    <!--这里不能使用resultType=“order”,因为order中没有user中的字段,只有一个user对象-->
    <select id="findAll" resultMap="orderMap">
        SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id
    </select>

</mapper>


一对多查询的模型

用户表和订单表的关系为,一个用户有多个订单,一个当但只从属一个用户
一对多查询需求:查询一个用户,与此同时查询出该用户具有的订单
在这里插入图片描述

select *,o.id oid from user u,orders o where u.id=o.uid

在这里插入图片描述

修改User实体

在这里插入图片描述

package com.zg.domain;

import java.util.Date;
import java.util.List;

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;

    //描述当前用户存在哪些订单
    private List<Order>  orderList;

    public List<Order> getOrderList() {
        return orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", orderList=" + orderList +
                '}';
    }

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getBirthday() {
        return birthday;
    }

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

创建UserMapper接口

package com.zg.mapper;

import com.zg.domain.User;

import java.util.List;

public interface UserMapper {
    public List<User> findAll();

}

配置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.zg.mapper.UserMapper" >

    <resultMap id="userMap" type="user">
        <id column="uid" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
        <!--配置集合信息-->
        <!--property:集合名称 ofType:当前集合中的数据类型-->
        <collection property="orderList" ofType="order">
            <!--封装order的数据-->
            <id column="oid" property="id"></id>
            <result column="ordertime" property="ordertime"></result>
            <result column="total" property="total"></result>
        </collection>
    </resultMap>

    <select id="findAll" resultMap="userMap">
        select *,o.id oid from user u,orders o where u.id=o.uid
    </select>


</mapper>


测试

 @Test//测试一对多
    public void test2() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.findAll();
        for (User user : userList) {
            System.out.println(user);
        }



        sqlSession.close();
    }

在这里插入图片描述

多对多查询

用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询该用户的所有角色
在这里插入图片描述

select * from user u,sys_user_role ur ,sys_role r where u.id=ur.userId and ur.roleId=r.id

在这里插入图片描述

创建Role实体,修改User实体

在这里插入图片描述

添加UserMapper接口

package com.zg.mapper;

import com.zg.domain.User;

import java.util.List;

public interface UserMapper {
    public List<User> findAll();

    public List<User> findUserAndRoleAll();

}

配置UserMapper.xml

<resultMap id="userRoleMap" type="user">
        <!--user信息的封装-->
        <id column="userid" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>

        <!--user内部的rolelist信息-->
        <collection property="roleList" ofType="role">
            <id column="roleid" property="id"></id>
            <result column="roleName" property="roleName"></result>
            <result column="roleDesc" property="roleDesc"></result>
        </collection>

    </resultMap>
    <select id="findUserAndRoleAll" resultMap="userRoleMap">
        select * from user u,sys_user_role ur ,sys_role r where u.id=ur.userId and ur.roleId=r.id
    </select>

测试代码

 @Test//测试多对多
    public void test3() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userAndRoleAll = mapper.findUserAndRoleAll();
        for (User user : userAndRoleAll) {
            System.out.println(user);
        }


        sqlSession.close();
    }

在这里插入图片描述

这篇关于MyBatis多表操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!