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>


一對多查詢的模型

用戶表和訂單表的關系為,一個用戶有多個訂單,一個當但隻從屬一個用戶
一對多查詢需求:查詢一個用戶,與此同時查詢出該用戶具有的訂單

在這裡插入圖片描述

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;
    }
}

在這裡插入圖片描述

修改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多表操作的文章就介紹到這瞭,更多相關MyBatis多表操作內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: