gpt4 book ai didi

java - Spring boot 2.0.4.RELEASE 默认情况下 fetch eager

转载 作者:行者123 更新时间:2023-12-01 07:00:59 24 4
gpt4 key购买 nike

我正在将 Spring Boot 与 JPA (hibernate) 结合使用,在转向 Spring Boot 之前,我将 Spring data JPA 与 Hibernate 一起使用,默认情况下是立即加载属性值并延迟加载集合。

在 Spring Boot JPA 中,默认情况下会急切地获取以下内容,为什么?角色将在用户内部返回,但它们应该为空

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;

这就是我遵循的例子 https://medium.com/@gustavo.ponce.ch/spring-boot-spring-mvc-spring-security-mysql-a5d8545d837d

我已将 application.properties 编辑为以下内容:

# ===============================
# = JPA / HIBERNATE
# ===============================
spring.jpa.show-sql = true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

# ==============================================================
# = Spring Security / Queries for AuthenticationManagerBuilder
# ==============================================================
spring.queries.users-query=select email, password, active from user where email=?
spring.queries.roles-query=select u.email, r.role from user u inner join user_role ur on(u.id=ur.user_id) inner join role r on(ur.role_id=r.id) where u.email=?

================================================== ===========================我尝试在用户实体中添加此关系:

@Entity
@Table(name = "user")
@Getter
@Setter
public class User {

@OneToMany(mappedBy = "user")
private List<Test> tests;
}

测试将在此处急切地获取:

@Transactional
@Override
public List<User> getAllUsers() {
List<User>users=userRepository.findAll();
return users;
}

我不明白为什么这是默认的而不是延迟加载。

最佳答案

你错了。默认情况下,每个以 toMany 结尾的映射都是延迟获取的。
从 Spring 源文件复制:

@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface ManyToMany {

// rest of the annotation properties are omitted for better readability

FetchType fetch() default LAZY;
}

关于java - Spring boot 2.0.4.RELEASE 默认情况下 fetch eager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52375117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com