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

相关推荐
VX:Fegn08953 小时前
计算机毕业设计|基于ssm + vue超市管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·课程设计
Mr.朱鹏4 小时前
Nginx路由转发案例实战
java·运维·spring boot·nginx·spring·intellij-idea·jetty
VX:Fegn08955 小时前
计算机毕业设计|基于springboot + vue酒店管理系统(源码+数据库+文档)
vue.js·spring boot·课程设计
代码丰7 小时前
SpringAI+RAG向量库+知识图谱+多模型路由+Docker打造SmartHR智能招聘助手
人工智能·spring·知识图谱
Java天梯之路7 小时前
Spring Boot 钩子全集实战(七):BeanFactoryPostProcessor详解
java·spring boot·后端
wr2005148 小时前
第二次作业,渗透
java·后端·spring
短剑重铸之日8 小时前
《SpringCloud实用版》生产部署:Docker + Kubernetes + GraalVM 原生镜像 完整方案
后端·spring cloud·docker·kubernetes·graalvm
爬山算法8 小时前
Hibernate(67)如何在云环境中使用Hibernate?
java·后端·hibernate
女王大人万岁9 小时前
Go标准库 io与os库详解
服务器·开发语言·后端·golang
露天赏雪9 小时前
Java 高并发编程实战:从线程池到分布式锁,解决生产环境并发问题
java·开发语言·spring boot·分布式·后端·mysql