我有這個物體:
@Entity
public class PlantArea {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_plantarea")
@SequenceGenerator(name = "seq_plantarea", allocationSize = 1)
@Column(nullable = false, updatable = false)
private Long id;
private String code;
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="plantid", nullable = false)
private Plant plant;
}
在回購中,我得到了所有像這樣的植物區:
@Override
public List<PlantArea> getPlantAreas() {
return plantAreaRepository.findAll();
}
所以,沒什么特別的。
我對此有兩個問題:
Hibernate 觸發兩個查詢:一個用于選擇植物區域,另一個用于選擇相關植物。我怎樣才能避免這種情況,我怎樣才能強制休眠只做一個查詢?就像在 sql 中(偽):選擇所有植物區域內連接植物。我想我必須寫一些 jpql/hql,不管是什么查詢?
用 simple 查詢植物區域
findAll()會得到這個 json 結果:[ {“id”:1,“代碼”:“122”,“名稱”:“汽車”,“工廠”:{“id”:1,“代碼”:“130”,“位置”:“某個城市", "company": { "id": 1, "name": "test company long name", "shortName": "test company " } } } ]
如您所見,每家工廠也都有一家公司。所以,我得到了相關物件的完整鏈:植物 -> 植物 -> 公司。問題是,我怎樣才能抑制company物件?基本上我需要這樣的查詢(偽sql):
select plantarea.*, plant.*, company.* from plantarea
inner join plant on plantarea.plant_id=plant.id
inner join company on plant.company_id=company.id
uj5u.com熱心網友回復:
(1) 選擇那些額外的查詢Plant是因為您配置FetchType.EAGER了PlantArea.plant其中的代碼異味(有關詳細資訊,請參閱此內容)。要解決它,您可以使用 ' fetch join ' 來獲取串列PlantArea及其Plant.Something 喜歡:
public interface PlantAreaRepository extends JpaRepository<PlantArea, Long> {
@Query("select p from PlantArea p left join fetch p.plant")
List<PlantArea> findAllWithPlant();
}
(2) 對我來說另一種代碼味道。對于一個不平凡的應用程式,我寧愿為 API JSON 回應創建另一個 DTO,而不是直接將物體暴露給外界。它只會讓您難以發展您的應用程式,因為每當您更改物體時,您都必須擔心它可能會影響現有的 API 客戶端。因此,只需創建一個單獨的 DTO,其結構與您的 API 回應完全相同。然后映射PlantArea到這些 DTO 并回傳給客戶端。
@Data
public class PlantAreaDto {
private Long id;
private String code;
private String name;
private PlantDto plant;
}
@Data
public class PlantDto {
private Long id;
private String location;
}
uj5u.com熱心網友回復:
@Ken Chan 建議的替代方法:
使用“物體圖”而不是 jpql: jpql “join fetch” vs EntityGraph (這似乎更具宣告性)
使用“@jacksonidentityinfo”而不是撰寫(和映射)自定義 DTO(不撰寫自定義 DTO 可能適用于簡單的用例,它可能不一定總是符合代碼氣味) https://stackoverflow.com /a/47351918 https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonIdentityInfo.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413710.html
標籤:
上一篇:通過JPA原生查詢更新
