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可以加快级联查询

相关推荐
Victor35612 小时前
https://editor.csdn.net/md/?articleId=139321571&spm=1011.2415.3001.9698
后端
Victor35612 小时前
Hibernate(89)如何在压力测试中使用Hibernate?
后端
灰子学技术14 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
风流倜傥唐伯虎14 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Gogo81615 小时前
BigInt 与 Number 的爱恨情仇,为何大佬都劝你“能用 Number 就别用 BigInt”?
后端
fuquxiaoguang15 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
毕设源码_廖学姐16 小时前
计算机毕业设计springboot招聘系统网站 基于SpringBoot的在线人才对接平台 SpringBoot驱动的智能求职与招聘服务网
spring boot·后端·课程设计
顾北1216 小时前
MCP服务端开发:图片搜索助力旅游计划
java·spring boot·dubbo
昀贝16 小时前
IDEA启动SpringBoot项目时报错:命令行过长
java·spring boot·intellij-idea
野犬寒鸦17 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法