大家好,我是神韵,是一个技术&生活博主。出文章目的主要是两个,一是好记忆不如烂笔头,记录总结中提高自己。二是希望我的文章可以帮到大家。欢迎来点赞打卡,你们的行动将是我无限的动力。
本篇主题是:一行配置解决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
解决方法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
两张关联表代码
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;
}
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;
}