• 一行配置解决JPA + H2 测试时懒加载LazyInitializationException异常


    大家好,我是神韵,是一个技术&生活博主。出文章目的主要是两个,一是好记忆不如烂笔头,记录总结中提高自己。二是希望我的文章可以帮到大家。欢迎来点赞打卡,你们的行动将是我无限的动力。
    本篇主题是:一行配置解决JPA + H2 测试时懒加载LazyInitializationException异常

    一、解决:
    1、直接在配置文件中加下面配置

    spring:

    2、在Entity 下配置实时查询

    fetch = FetchType.EAGER

    还有很多,这里说两种够用了~

    二、场景复原:多级关联的情况下,查询的时候抛出异常:

    Unable to evaluate the expression Method threw ‘org.hibernate.LazyInitializationException’ exception.

    在这里插入图片描述
    解决方法1:
    直接在test配置文件中加下面配置

    spring:
      jpa:
        hibernate:
        properties:
          hibernate:
            enable_lazy_load_no_trans: true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    解决方法2:
    开启实时查询

    fetch = FetchType.EAGER

    在这里插入图片描述

    这里贴一下配置文件 application-test.yml

    spring:
      datasource:
    #    data: classpath:sql/boot_backend_init.sql
      h2:
        console:
          enabled: true
      #不存在会自动创建/包括库、表等
      jpa:
        hibernate:
          #测试时每次删掉
          ddl-auto: create-drop
        properties:
          hibernate:
            enable_lazy_load_no_trans: true
            dialect: org.hibernate.dialect.H2Dialect
            show-sql: true
        defer-datasource-initialization: true
        generate-ddl: true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    两张关联表代码
    Account

    @Getter
    @Setter
    @Entity
    @Table(name = "account")
    public class Account {
        @Id
        @Column(name = "accountNumber")
        private String accountNumber;
    
        @ManyToOne
        @JoinColumn(name = "customerNumber", referencedColumnName = "customerNumber")
        private Customer customer;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    customer

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    @Entity
    @Table(name = "customer")
    public class Customer {
        @Id
        @Column(name = "customerNumber")
        private String customerNumber;
    
        /**
         * 1 对 多关系,一个客户可能有多个账号
         */
        @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, orphanRemoval = true)
        private List<Account> accounts;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    python 接口测试 request 模块的学习记录
    Java EnumSet clone()方法具有什么功能
    快速入门Git
    第六章 图论 16 AcWing 1558. 加油站
    Python列表基础与高级应用详解
    otn 709帧结构
    微信小程序使用 npm 安装第三方包
    飞腾性能调优
    【Linux基础】3.1任务调度
    实在智能:RPA领域如何使用CRM实现业务精益化管理
  • 原文地址:https://blog.csdn.net/qq_41055045/article/details/126104301