JPA中的EntityGraph

前言

在使用JPA进行数据库访问时,可能会遇到n+1问题,也就是在查询关联实体时,jpa会额外执行查询操作,使用EntityGraph时,这是JPA推出优化解决效率问题的注解,EntityGraph则直接在查询语句的时候,直接用到用到Left Join,优化了数据库的性能

JPA关联表

实体类

定义一个实体类

less 复制代码
@Data
@Entity
@FieldNameConstants
@Table(name = "machine_room")
@NamedEntityGraph(name = "MachineRoom.machineRoomInformationList", attributeNodes = {
        @NamedAttributeNode(value = "machineRoomInformationList"),
})
public class MachineRoom {


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;


    private String projectName;


    @OneToMany(mappedBy = "machineRoom", cascade = CascadeType.ALL)
    private List<MachineRoomInformation> machineRoomInformationList;

}

关联实体类

less 复制代码
@Data
@Entity
@FieldNameConstants
@Table(name = "machine_room_information")
public class MachineRoomInformation {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String attributeKey;


    private String attributeValue;


    @ManyToOne
    @JoinColumn(name = "machine_room_id")
    private MachineRoom machineRoom;
}

定义dao层

java 复制代码
public interface IMachineRoomRepository extends JpaRepository<MachineRoom, Long> {


    @Transactional(rollbackFor = Exception.class)
    void deleteByIdIn(List<Long> ids);
    
    List<MachineRoom> findByIdIn(List<Long> ids);
}

数据库插入一条数据

接口

typescript 复制代码
@GetMapping("/hello3")
public String hello3() {
    List<MachineRoom> machineRoomList = iMachineRoomRepository.findByIdIn(List.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 102L));
    MachineRoomDto machineRoomDto = new MachineRoomDto();
    for (MachineRoom machineRoom : machineRoomList) {
        BeanUtils.copyProperties(machineRoom, machineRoomDto);
    }
    return "success";
}

会发两条sql语句

加上@EntityGraph注解

java 复制代码
public interface IMachineRoomRepository extends JpaRepository<MachineRoom, Long> {


    @Transactional(rollbackFor = Exception.class)
    void deleteByIdIn(List<Long> ids);

    @EntityGraph(value = "MachineRoom.machineRoomInformationList")
    List<MachineRoom> findByIdIn(List<Long> ids);
}

会产生一条left join语句

总结

使用EntityGraph可以加快级联查询

相关推荐
Victor356几秒前
Netty(13)Netty中的事件和回调机制
后端
程序员游老板38 分钟前
基于SpringBoot3_vue3_MybatisPlus_Mysql_Maven的社区养老系统/养老院管理系统
java·spring boot·mysql·毕业设计·软件工程·信息与通信·毕设
码事漫谈1 小时前
VS Code 1.107 更新:多智能体协同与开发体验升级
后端
码事漫谈1 小时前
从概念开始开始C++管道编程
后端
@淡 定1 小时前
Spring中@Autowired注解的实现原理
java·后端·spring
serendipity_hky2 小时前
【go语言 | 第2篇】Go变量声明 + 常用数据类型的使用
开发语言·后端·golang
疯狂的程序猴2 小时前
App Store上架完整流程与注意事项详解
后端
开心就好20252 小时前
把 H5 应用上架 App Store,并不是套个壳这么简单
后端
tirelyl2 小时前
LangChain.js 1.0 + NestJS 入门 Demo
后端
王中阳Go背后的男人3 小时前
GoFrame vs Laravel:从ORM到CLI工具的全面对比与迁移指南
后端·go