【问题标题】:Why does @EntityGraph not load EAGER scince Spring version 2.2.5?为什么 @EntityGraph 从 Spring 2.2.5 版开始不加载 EAGER?
【发布时间】:2020-04-10 13:35:49
【问题描述】:

在Spring Boot 2.2.5之前@EntityGraph用来加载EAGER,但是在2.2.5之后我需要将EAGER添加到attributePaths,例如attributePaths = {"image", "roles"}

@EntityGraph 如何工作或者我做错了什么。当我更改为较新的版本 2.2.4 -> 2.2.5

时出现了问题
@Entity
@Getter
@Setter
public class Employee {

@Column
private String email;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
        name = "employees_roles",
        joinColumns = @JoinColumn(name = "employees_id", nullable = false, referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "roles_id", nullable = false, referencedColumnName = "id")
)
private Set<Role> roles;


@JoinColumn(name = "image_id")
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private Image image;
}

@Repository
interface EmployeeRepository extends JpaRepository<Employee, Long> {

@EntityGraph(attributePaths = "image")
Optional<Employee> findByEmailIgnoreCase(String email);
}

@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/employee", produces = MediaType.APPLICATION_JSON_VALUE)
public class EmployeeController {

private final EmployeeService employeeService;

@GetMapping(value = "/login")
public ResponseEntity<String> login(Principal user) throws IOException {
    Employee employee = employeeService.findByEmailIgnoreCase(user.getName())
            .orElseThrow(() -> new UsernameNotFoundException(USER_NOT_FOUND));

    return ResponseEntity.ok(employee);
}
}

【问题讨论】:

    标签: spring-boot eager-loading entitygraph


    【解决方案1】:

    attributePaths of @EntityGraph 采用 String[] 您正在使用 String 试试这个方法

    @EntityGraph(attributePaths = {"image"})
    

    【讨论】:

    • org.hibernate.LazyInitializationException: 延迟初始化角色集合失败:com.test.Employee.roles,
    • 您已经在为角色使用 FetchType.EAGER,这可能会导致问题
    • 这不是因为急切,因为在我使用 2.2.4 之前它运行良好
    • 在我的情况下,解决方案有点不同,但你帮了很多忙。这是解决方案:@EntityGraph(attributePaths = "galleryImages.image", type = EntityGraph.EntityGraphType.LOAD)
    【解决方案2】:

    您的问题与 Hibernate 5.4.12.Final 中包含的更改有关,该更改包含在 Springboot 2.2.5 中。

    https://github.com/hibernate/hibernate-orm/pull/3164/files

    为避免此问题,您需要使用 QueryHints。 (javax.persistence.fetchgraphjavax.persistence.loadgraph

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多