我有 2 個班級,Aircraft并且具有從到Operator的一對多關系。來自 JPA 存盤庫的對表(大約 10k 行)的呼叫運行速度很快,只需幾秒鐘,但對表(大約 65k 行)的呼叫有時需要幾分鐘才能執行。OperatorAircraftfindAll()OperatorfindAll()Aircraft
另外,我注意到運算子上的操作僅在控制臺中findAll()生成 1 個休眠查詢,而在飛機上,它會在飛機表上生成 1 個查詢,并且對具有約束的運算子生成許多其他查詢,我認為這不是想要的。SELECTSELECTSELECTwhere operator0_.id=?
從 Controller 類到 Service 類的 GET 請求呼叫 findAll(),結果用于將 Aircraft 物件映射到 AircraftDTO 物件,該物件還包括操作員名稱。
如何解決此問題以使運行中的findAll()查詢Aircraft更快?
注意:由于在這種情況下缺乏相關性,一些類屬性被洗掉
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Aircraft implements Serializable {
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "aircraft_sequence"
)
@SequenceGenerator(
name = "aircraft_sequence",
allocationSize = 1
)
@Column(nullable = false, updatable = false)
private Long id;
@ManyToOne
@JoinColumn(name="operator_id", nullable=false)
private Operator operator;
private String registration;
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Operator implements Serializable {
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "operator_sequence"
)
@SequenceGenerator(
name = "operator_sequence",
allocationSize = 1
)
@Column(nullable = false, updatable = false)
private Long id;
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy="operator")
@JsonIgnore
private Set<Aircraft> aircraft;
}
public interface AircraftRepository extends JpaRepository<Aircraft, Long> {
}
public interface OperatorRepository extends JpaRepository<Operator, Long> {
}
Hibernate: select aircraft0_.id as id1_0_, aircraft0_.operator_id as operator7_0_, aircraft0_.registration as registra5_0_ from aircraft aircraft0_
Hibernate: select operator0_.id as id1_2_0_, operator0_.name as name12_2_0_ from operator operator0_ where operator0_.id=?
Hibernate: select operator0_.id as id1_2_0_, operator0_.name as name12_2_0_ from operator operator0_ where operator0_.id=?
Hibernate: select operator0_.id as id1_2_0_, operator0_.name as name12_2_0_ from operator operator0_ where operator0_.id=?
Hibernate: select operator0_.id as id1_2_0_, operator0_.name as name12_2_0_ from operator operator0_ where operator0_.id=?
Hibernate: select operator0_.id as id1_2_0_, operator0_.name as name12_2_0_ from operator operator0_ where operator0_.id=?
Hibernate: select operator0_.id as id1_2_0_, operator0_.name as name12_2_0_ from operator operator0_ where operator0_.id=?
Hibernate: select operator0_.id as id1_2_0_, operator0_.name as name12_2_0_ from operator operator0_ where operator0_.id=?
...and so on
uj5u.com熱心網友回復:
問題是存在一個回圈依賴,通過覆寫類findAll()中的AircraftRepository并包括JOIN FETCH
public interface AircraftRepository extends JpaRepository<Aircraft, Long> {
@Override
@Query(value = "SELECT distinct a"
" FROM Aircraft a "
" JOIN FETCH a.operator ")
List<Aircraft> findAll();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/513447.html
