springboot结合MyBatis实现懒加载(延时加载)

12 篇文章 69 订阅
3 篇文章 0 订阅

什么是懒加载?

        个人理解的懒加载就是在需要查询关联信息的时候去加载查询语句,在不需要的时候就不去执行查询。

        在mybatis中,一对一关联的 association 和一对多的collection可以实现懒加载。resultMap可以实现高级映射,所以Mybatis在实现懒加载时要使用 resultMap,不能使用 resultType。

实例

1、mybatis默认是没有开启懒加载的,要使用懒加载,需要先在全局配置中开启懒加载配置;

server.port=8081

#开启懒加载
mybatis.configuration.lazy-loading-enabled=true
#false 为按需加载
mybatis.configuration.aggressive-lazy-loading=false

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_mybatis
spring.datasource.username=root
spring.datasource.password=root
        
#开启驼峰命名,打印sql
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

        注释:序列化和反序列化的内容待更新(后期我会在这里附上链接)

2、创建User和Account实体类并在数据库中创建出对应的表

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {  //将User类序列化
    private Integer id;  //用户id
    private String username;  //用户名
    private Date birthday;    //出生日期
    private String sex;       //性别
    private String address;   //地址
    /*
     * 要查询用户信息,用户信息下有对应的账户信息,因此我们需
     * 要创建一对多关系映射:主表实体应该包含从表实体的集合引用
     * */
    private List<Account> accounts;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private Integer id;
    private Integer uid;
    private Double money;
    //,一个账号只能对应一个用户,从表实体应该包含一个主表实体的对象引用
    private User user;
}

3、创建 IUserMapper和IAccountMapper接口文件

        方式一、如果在这里采用的是Mapper代理加载xxxMapper.xml配置文件(没有配置全局扫描的情况下),所以接口和xml文件需要满足以下几个条件(如下情况所示)

  • 接口要和xml文件同名且在同一个包下,也就是xml文件中的namespace是接口的全类名
  • 接口中的方法名和xml文件中定义的id一致
  • 接口中输入的参数类型要和xml中定义的parameType保持一致
  • 接口的返回值类型要和xml中定义的resultType保持一致

方式二、我们可以将xml文件抽取出来,然后在主启动类中配置全局扫描

         具体代码如下:

        (1)先在主配置类中进行配置扫描mapper文件;

@SpringBootApplication
@MapperScan(value = "com.lazyload.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

        (2)IUserMapper.java接口;

@Mapper
/*数据库操作接口:我们当然也可以通过实现类实现,但是mybatis环境帮我们配置了,所以我们不用写实现类*/
public interface IUserMapper {
    //查询所有用户,同时获取到用户下所有的账户信息
    List<User> findAll();
    //查询一个
    User findUserById(int userId);
}

        (3)IUserMapper.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.lazyload.mapper.IUserMapper">

    <!--写入user的resultMap:将user和数据库对应
    作用:建立SQL查询结果字段与实体属性的映射关系
    -->
    <resultMap id="userAccountMap" type="com.lazyload.entites.User">
        <!--主键字段-->
        <!--column所表示的是数据库中的字段名称-->
        <id property="id" column="id"></id>
        <!--非主键字段-->
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <!--Userx下对应的对应Account账户的信息:配置user对象下account的映射-->
        <collection property="accounts"  select="findUserById" column="id"></collection>
    </resultMap>
    <!--查询所有-->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>

    <!--查询一个通过id-->
    <select id="findUserById" parameterType="int" resultType="com.lazyload.entites.User">
        select * from user where id=#{id}
    </select>
</mapper>

        另外一种情况: 

resultMap

      (4)IAccountMapper.java接口;

@Mapper
public interface IAccountMapper {
    /*查询所有*/
    List<Account> findAllAccount();
    /*两表联查
    * 根据用户id查询账户信息
    */
    List<Account> findAccountByUid(int uid);
}

        (5)IAccountMapper.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.lazyload.mapper.IAccountMapper">

    <!--将Account的信息和User的信息封装到ResultMap中去-->
    <!--  property表示java实体类中属性的名称,javaType表示属性的类型,ofType表示泛型,column表示应用查询的某列 select表示需要执行的sql语句 fetchType表示是否开启延迟加载eager取消延迟加载,lazy开启延迟加载,默认开启 -->
    <resultMap id="userAccountMap" type="com.lazyload.entites.Account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--一对一的映射关系:配置封装的内容
        select属性指定的内容:查询用户的唯一标识【com.itheima.dao.IAccountMapper+方法名(就是接口中的)】
        column属性指定的内容:根据id查询时,所需要的参数的值(根据id来查询数据库的)
        -->
        <association property="user" column="uid" javaType="com.lazyload.entites.User" select="findAccountByUid"></association>
    </resultMap>

    <!--封装的查询所有-->
    <select id="findAllAccount" resultMap="userAccountMap">
        select * from account
    </select>

    <!--根据用户id查询账户列表-->
    <select id="findAccountByUid" parameterType="integer" resultType="com.lazyload.entites.Account">
        select * from account where uid=#{uid}
    </select>

</mapper>

4、测试

    @Test
    public void test1(){
        List<User> all = iUserMapper.findAll();
        for (User user:all) {
            System.out.println(user.getAccounts());
        }
    }

    @Test
    public void test2(){
        List<User> all = iUserMapper.findAll();
        for (User user:all) {
            System.out.println(user.getUsername());
        }
    }

         如果只访问用户的基础信息而不访问账户,此时是不会触发懒加载的,只会查询单表;若果访问了账户,那么则会触发懒加载,查询出用户的id后,再根据id去获取账号。

        与没有开启延迟加载的区别是,延迟加载只有使用到才会使用sql去查询,并且是一个一个输出。而非延迟加载是全部sql都执行一遍。

5、使用总结

  • 开启全局懒加载;
  • 先单表查询,将查询结果放到resultMap,将关联的列对应的值通过column(必须)传递到另外的表对应的具体查询方法;
  • 当需要时再去执行对应的方法;
  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SpringBootMyBatis实现分区表可以通过使用MyBatis-Plus插件实现MyBatis-Plus是MyBatis的增强工具,在MyBatis的基础上提供了更多的功能和便捷的操作方式,包括分区表的实现。 下面是一个简单的示例,演示如何在SpringBootMyBatis实现分区表: 1. 首先,在pom.xml文件中添加MyBatis-Plus和Druid的依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 2. 然后,在application.properties文件中配置Druid数据源和MyBatis-Plus的相关配置: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Druid 数据源配置 spring.datasource.druid.initial-size=5 spring.datasource.druid.max-active=20 spring.datasource.druid.min-idle=5 spring.datasource.druid.test-on-borrow=true # MyBatis-Plus 配置 mybatis-plus.mapper-locations=classpath:mapper/*.xml mybatis-plus.configuration.cache-enabled=false mybatis-plus.configuration.map-underscore-to-camel-case=true mybatis-plus.configuration.default-fetch-size=100 ``` 3. 接下来,在MyBatis的Mapper文件中使用分区表的SQL语句: ``` <select id="getUserById" resultType="com.example.demo.entity.User"> SELECT * FROM user_${id % 10} WHERE id = #{id} </select> ``` 这里的user_${id % 10}表示使用id模10的结果作为分区表的后缀,即将数据按照id模10的结果分散到10个不同的表中。 4. 最后,在SpringBoot应用中调用Mapper方法即可实现分区表的查询: ``` @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.getUserById(id); } ``` 至此,我们已经完成了在SpringBootMyBatis实现分区表的过程。当然,实际场景中可能会更复杂,需要结合具体业务需求进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星悦糖

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值