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

相关推荐
i***66508 小时前
SpringBoot实战(三十二)集成 ofdrw,实现 PDF 和 OFD 的转换、SM2 签署OFD
spring boot·后端·pdf
qq_12498707538 小时前
基于springboot的建筑业数据管理系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·毕业设计
一 乐8 小时前
宠物管理|宠物共享|基于Java+vue的宠物共享管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·springboot·宠物
a crazy day9 小时前
Spring相关知识点【详细版】
java·spring·rpc
IT_陈寒9 小时前
Vite 5.0实战:10个你可能不知道的性能优化技巧与插件生态深度解析
前端·人工智能·后端
z***3359 小时前
SQL Server2022版+SSMS安装教程(保姆级)
后端·python·flask
foundbug9999 小时前
配置Spring框架以连接SQL Server数据库
java·数据库·spring
-大头.9 小时前
JVM框架实战指南:Spring到微服务
jvm·spring·微服务
p***930310 小时前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis