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

相关推荐
AAA修煤气灶刘哥2 分钟前
Lombok坑哭了!若依框架一行@Data炸出Param为null,我卡了一下午才发现BaseEntity的猫腻
java·后端
SimonKing27 分钟前
手搓MCP客户端动态调用多MCP服务,调用哪个你说了算!
java·后端·程序员
写bug写bug42 分钟前
分布式锁的使用场景和常见实现(上)
分布式·后端·面试
Ali酱1 小时前
2周斩获远程offer!我的高效求职秘诀全公开
前端·后端·面试
Q_Q19632884752 小时前
python基于Hadoop的超市数据分析系统
开发语言·hadoop·spring boot·python·django·flask·node.js
小乌龟不会飞2 小时前
【SpringBoot】统一功能处理
java·spring boot·后端
刘小吉2 小时前
java net 配置局域网受信任的https
后端
coolflyr_reg2 小时前
禅道集成Firebase PHP-JWT
后端
似水流年流不尽思念2 小时前
常见的排序算法有哪些?它们的平均时间复杂度是多少?
后端·算法