• 一行配置解决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
  • 相关阅读:
    项目上线后,老板喜提法拉利
    基于linux的操作系统的通用启动流程(一)
    android设计模式-builder模式
    paddle2.0简要安装过程
    bootstrap企业网站前端模板
    鸿鹄工程项目管理系统em Spring Cloud+Spring Boot+前后端分离构建工程项目管理系统
    基于nodejs+vue酒店综合服务[程序+论文+开题]-计算机毕业设计
    9、Spring之推断构造方法源码解析
    数据结构_栈和队列
    WebDAV之π-Disk派盘 + 言叶
  • 原文地址:https://blog.csdn.net/qq_41055045/article/details/126104301