MyBatis的关联查询和延迟加载

2023-12-28 06:12:46

MyBatis的关联查询

1.什么是关联查询

  • 实体间的关系(拥有 has、属于 belong)

    • OneToOne:一对一关系(account ←→ user)

    • OneToMany:一对多关系(user ←→ account)

    • ManyToMany:多对多关系(user ←→ role)

  • 什么是关联查询

    当访问关系的一方时,如果需要查看与之关联的另一方数据,则必须使用表链接查询,将查询到的另一方数据,保存在本方的属性中

  • 关联查询的语法

    指定“一方”关系时(对象),使用< association javaType="" >

    指定“多方”关系时(集合),使用< collection ofType="" >

2.一对一查询

需求:查询账户信息,关联查询用户信息。

分析:因为一个账户信息只能供某个用户使用,所以从查询账户信息出发关联查询用户信息为一对一查询。

2.1.pojo
package com.jyx.pojo;

public class Account {
    private Integer id;
    private  Integer uid;
    private Integer money;
    private User user;

    public User getUser() {
        return user;
    }

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

    public Account() {
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                ", 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 Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }

    public Account(Integer id, Integer uid, Integer money) {
        this.id = id;
        this.uid = uid;
        this.money = money;
    }
}

package com.jyx.pojo;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private String password;

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

    public String getPassword() {
        return password;
    }

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

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public Date getBirthday() {
        return birthday;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }


}

2.2.mapper
package com.jyx.mapper;

import com.jyx.pojo.Account;

public interface AccountDao {
   Account getAccountById(Integer id);
}

<?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.jyx.mapper.AccountDao">
    <!--
        id:和接口方法名保持一致
        resultType:和接口返回类型保持一致
    -->
    <resultMap id="getAccountByIdResultMap" type="account">
        <id column="aid" property="id"></id>
        <result column="uid" property="uid"></result>
        <result column="money" property="money"></result>
        <!--
            一对一查询使用association标签
            property="user"Account的属性名
            javaType="user":等价于resultType
        -->
        <association property="user" javaType="user">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="password" property="password"></result>
            <result column="birthday" property="birthday"></result>
            <result column="sex" property="sex"></result>
            <result column="address" property="address"></result>
        </association>

    </resultMap>
    <select id="getAccountById" parameterType="int" resultMap="getAccountByIdResultMap">
        SELECT a.id aid ,a.uid uid ,a.money money ,u.* FROM account a JOIN user u on a.uid=u.id where a.id=#{id}
    </select>
</mapper>

3.一对多查询

需求:查询所有用户信息及用户关联的账户信息。

分析:用户信息和他的账户信息为一对多关系,并且查询过程中如果用户没有账户信息,此时也要将用户信息查询出来,此时左外连接查询比较合适。

3.1.pojo
package com.by.pojo;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
//一方
public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    //多方
    private List<Account> accountList;

    public Integer getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public List<Account> getAccountList() {
        return accountList;
    }

    public void setAccountList(List<Account> accountList) {
        this.accountList = accountList;
    }

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

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

    public Date getBirthday() {
        return birthday;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

3.2.mapper
package com.by.mapper;

import com.by.pojo.User;

import java.util.List;

public interface UserMapper {
    User getUserById(Integer id);
}
<?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">
<!--
    namespace:保持唯一,推荐写接口全类名

    Map<namespace+id, MappedStatement(sql, resultType)>
       <namespace+id, MappedStatement(sql, resultType)>
       <namespace+id, MappedStatement(sql, resultType)>
       <namespace+id, MappedStatement(sql, resultType)>

-->
<mapper namespace="com.by.mapper.UserMapper">

    <resultMap id="getUserByIdResult" type="com.by.pojo.User">
        <id column="id" property="id"></id>
        <result column="username" property="username"/>
        <result column="address" property="address"/>
        <result column="sex" property="sex"/>
        <result column="birthday" property="birthday"/>

        <!--一对多使用collection标签指定数据的封装规则-->
        <collection property="accountList" ofType="com.by.pojo.Account">
            <id column="aid" property="id"></id>
            <result column="uid" property="uid"></result>
            <result column="money" property="money"></result>
        </collection>
    </resultMap>

    <select id="getUserById" parameterType="int" resultMap="getUserByIdResult">
        SELECT u.*, a.id aid, a.uid uid, a.money money FROM user u LEFT JOIN account a ON u.id=a.uid WHERE u.id=#{id}
    </select>
</mapper>

3.3.测试
@Test
    public void getUserById(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.getUserById(1);
        System.out.println(user);
    }

4.多对多查询

需求:查询角色及角色赋予的用户信息。

分析:一个用户可以拥有多个角色,一个角色也可以赋予多个用户,用户和角色为双向的一对多关系,多对多关系其实我们看成是双向的一对多关系。

在这里插入图片描述

4.1.pojo
package com.by.pojo;

import java.util.List;

//一方
public class Role {
    private Integer id;
    private String roleName;
    private String roleDesc;

    //多方
    private List<User> userList;

    public Integer getId() {
        return id;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                ", userList=" + userList +
                '}';
    }
}
4.2.mapper
package com.jyx.mapper;
import com.jyx.pojo.Role;
public interface RoleMapper {
    Role getRoleById(Integer id);

}

<?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.jyx.mapper.RoleMapper">

    <resultMap id="getRoleByIdResultMap" type="com.jyx.pojo.Role">
        <id column="rid" property="id"></id>
        <result column="role_name" property="roleName"></result>
        <result column="role_desc" property="roleDesc"></result>

        <!-- 结果映射 -->

        <!-- 指定关系表中数据的封装规则 -->
        <collection property="userList" ofType="com.jyx.pojo.User">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </collection>
    </resultMap>
    <select id="getRoleById" parameterType="int" resultMap="getRoleByIdResultMap">
        select r.id rid , r.role_name ,r.role_desc,u.* from user_role ur JOIN role r ON ur.rid=r.id JOIN user u ON ur.uid=u.id   where r.id=#{id}
    </select>

</mapper>
4.3.测试
 @Test
    public void getRoleById(){
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        Role roleList = mapper.getRoleById(1);
        System.out.println(roleList);
    }

MyBatis的延迟加载

1.什么是延迟加载?

开启延迟加载后,在真正使用数据的时候才发起级联查询,不用的时候不查询。

2.mapper

package com.jyx.mapper;

import com.jyx.pojo.User;

public interface UserDao {
    User getUserById(Integer id);
    User getUserById2(Integer id);

}
<?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.jyx.mapper.UserDao">
    <resultMap id="getUserById2ResultMap" type="com.jyx.pojo.User">
        <id column="id" property="id"></id>
        <result column="username" property="username"></result>
        <result column="address" property="address"></result>
        <result column="sex" property="sex"></result>
        <result column="birthday" property="birthday"></result>
        <!--延迟加载的一对多-->
        <!--
            property="accountList":属性名
            ofType="com.by.pojo.Account":集合的泛型,等价于resultType
            select="com.by.mapper.AccountMapper.selectAccountByUid":要调用的select标签的id
            column="id":传递给select查询的参数
            fetchType="lazy":局部开启懒加载
        -->
        <collection property="accountList"
                    ofType="com.jyx.pojo.Account"
                    select="com.jyx.mapper.AccountDao.selectAccountByUid"
                    column="id"
                    fetchType="lazy">
        </collection>

    </resultMap>
    <select id="getUserById2" parameterType="int" resultMap="getUserById2ResultMap">
        select * from user where id =#{id}; 
    </select>
</mapper>

fetchType=“lazy”:局部开启懒加载
配置全局延迟加载
mybatis-config.xml文件中

<settings>
        &lt;!&ndash;  打开延迟加载的开关  &ndash;&gt;
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
<?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.jyx.mapper.AccountDao">
    <select id="selectAccountByUid" parameterType="int" resultType="com.jyx.pojo.Account">
        SELECT * FROM account WHERE uid=#{uid}
    </select>
</mapper>

3.测试
    @Test
public void testGetUserById2(){
       //不执行延迟加载
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.getUserById2(41);
        System.out.println(user.getUsername());
        //执行延迟加载
        List<Account> accountList = user.getAccountList();
        for (Account account : accountList) {
            System.out.println(account);
        }

文章来源:https://blog.csdn.net/jyx_boy/article/details/135117962
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。