java - 如何设置 JPA 双向一对一同时避免 n+1 查询

我正在尝试调试两个具有双向一对一关系的实体。问题是这种关系导致 N+1 查询发生。当我运行 findAll() 时,我的 table 中的每个项目都会执行一个查询。

这是一个例子:我有两个实体

package ...;
import ...;

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor
@EqualsAndHashCode
@Getter
@Builder

@Entity
@Table(name = "tracker")
public class TrackerEntity {
    @Id
    @Column(name = "vehicleid")
    private UUID vehicleId;

    @Column(name = "trackerid")
    private String trackerId;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "vehicleid", referencedColumnName = "id")
    private VehicleEntity vehicleEntity;
}
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor
@EqualsAndHashCode
@Getter
@Builder

@Entity
@Table(name = "vehicle")
public class VehicleEntity {
    @Id
    private UUID id;

    @Column(name = "vehiclename")
    private String vehicleName;

    @OneToOne(mappedBy = "vehicleEntity", cascade = CascadeType.REMOVE, orphanRemoval = true)
    private TrackerEntity trackerEntity;
}

当我运行 vehicleRepository.findAll() 时,我得到以下调试日志:

2022-05-17 19:16:45.071 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.097 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.104 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.106 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.109 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.110 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.113 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.115 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.117 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.119 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.123 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.125 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.128 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.130 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.133 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.135 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.138 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.141 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.144 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_0_, vehicleent0_.vehiclename as vehiclen2_1_0_ from vehicle vehicleent0_ where vehicleent0_.id=?
2022-05-17 19:16:45.146 DEBUG 62639 --- [           main] org.hibernate.SQL                        : insert into vehicle (vehiclename, id) values (?, ?)
2022-05-17 19:16:45.246 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select vehicleent0_.id as id1_1_, vehicleent0_.vehiclename as vehiclen2_1_ from vehicle vehicleent0_
2022-05-17 19:16:45.253 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.258 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.259 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.261 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.262 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.264 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.265 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.267 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.269 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?
2022-05-17 19:16:45.271 DEBUG 62639 --- [           main] org.hibernate.SQL                        : select trackerent0_.vehicleid as vehiclei1_0_0_, trackerent0_.trackerid as trackeri2_0_0_ from tracker trackerent0_ where trackerent0_.vehicleid=?

我搜索了 N+1 JPA 查询问题,希望找到解决方案,并且大多数建议使用 EntityGraph 或“字节码增强”。我试过使用实体图,但仍然有 n+1 个查询,我不想使用字节码增强,因为应用程序必须作为微服务在云上运行。

更重要的一件事是我希望在删除车辆时删除跟踪器,但不应该在创建车辆时创建它们。

有没有什么办法解决这一问题?

我尝试过使用 Query 并加入 fetch:

public interface VehicleRepository extends JpaRepository<VehicleEntity, UUID> {

    @Override
    @Query("SELECT v FROM VehicleEntity v left outer join fetch v.trackerEntity t")
    <S extends VehicleEntity> List<S> findAll(Example<S> example);
}

它没有改变任何东西,仍然有 n+1 个查询。我试过 EntityGraph 也没有改变:

@Entity
@Table(name = "vehicle")
@NamedEntityGraph(name="vehicleGraph", attributeNodes = {@NamedAttributeNode("trackerEntity")})
public class VehicleEntity {
    @Id
    private UUID id;

    @Column(name = "vehiclename")
    private String vehicleName;

    @OneToOne(mappedBy = "vehicleEntity", cascade = CascadeType.REMOVE, orphanRemoval = true)
    private TrackerEntity trackerEntity;
}
public interface VehicleRepository extends JpaRepository<VehicleEntity, UUID> {

    @Override
    @EntityGraph(value = "vehicleGraph", type = EntityGraph.EntityGraphType.LOAD)
    <S extends VehicleEntity> List<S> findAll(Example<S> example);
}

回答1

您可以使用 EntityGraph 和延迟加载来优化它。我认为 VehicleEntity 是这里的拥有实体。在这种情况下, make fetch = FetchType.LAZYcascade = CascadeType.ALL 应该在拥有实体上。 EntityGraph可以定义2种方式

  1. 命名实体图
  2. AD-HOC 或未命名实体图

命名实体图:

您可以在拥有类上定义 NamedEntityGraph 并在 VehicleEntityRepository 接口中引用它

@NamedEntityGraph(name = "VehicleEntity.trackerEntity", attributeNodes = @NamedAttributeNode("trackerEntity"))
public class VehicleEntity {
}

Vehicle EntityRepository.java

public interface VehicleEntityRepository extends JpaRepository<VehicleEntity, UUID> {
     @EntityGraph(value = "VehicleEntity.trackerEntity", type = EntityGraphType.LOAD)
    List<VehicleEntity> findAll();
}

AD-HOC 实体图:

您不必定义任何 EntityGraph 注解 VehicleEntity 类而可以直接使用它的 Repository 接口

Vehicle EntityRepository.java

public interface VehicleEntityRepository extends JpaRepository<VehicleEntity, UUID> {
    @EntityGraph(attributePaths = { "trackerEntity" })
    List<VehicleEntity> findAll();
}

VehicleEntity.java

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor
@EqualsAndHashCode
@Getter
@Builder

@Entity
@Table(name = "vehicle")
@NamedEntityGraph(name = "VehicleEntity.trackerEntity", attributeNodes = @NamedAttributeNode("trackerEntity"))
public class VehicleEntity {
    @Id
    private UUID id;

    @Column(name = "vehiclename")
    private String vehicleName;

 
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "vehicleEntity")
    @JsonManagedReference
    private TrackerEntity trackerEntity;
}

TrackerEntity.java

package ...;
import ...;

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor
@EqualsAndHashCode
@Getter
@Builder

@Entity
@Table(name = "tracker")
public class TrackerEntity {
    @Id
    @Column(name = "id")
    private UUID id;

    @Column(name = "trackerid")
    private String trackerId;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vehicleid", referencedColumnName = "id")
@JsonBackReference
    private VehicleEntity vehicleEntity;
}

在使用 Jackson 时,您还可以使用 @JsonManagedReference@JsonBackReference 来防止嵌套提取或无限递归。