[英]Hibernate Select Queries Optimization
我正在尋找優化Hibernate select
查詢的最佳方法。
這是一個基本示例:
BDD模型1客戶-> n合約-> n選項
請求客戶端“ xxxx”的所有數據的最簡單方式是:
final Query hqlQuery = jdbcTemplate.createHQLQuery("from Client cli left join fetch cli.contracts con left join fetch con.options where cli.id=:idClient");
hqlQuery .setString("idClient", "xxxx");
Client client = (Client) hqlQuery.uniqueResult();
有時這是不可能的,因為要返回兩個數據。
因此,我拆分了請求,例如:
// Query 1
final Query hqlQueryClient = jdbcTemplate.createHQLQuery("from Client cli left join fetch cli.contracts where cli.id=:clientId");
hqlQueryClient.setString("clientId", "xxxx");
Client client = (Client) hqlQueryClient.uniqueResult();
List<String> listContractIds = new ArrayList<String>();
for (Contract contract : client.getContracts()) {
listContractIds.add(contract.getId());
}
// Query 2
final Query hqlQueryOptions = jdbcTemplate.createHQLQuery("from Option opt where opt.contract.id in(:contractIds)");
hqlQueryOptions.setParameterList("contractIds", listContractIds);
List<Option> options = hqlQueryClient.list();
但是,通過第二種方式,我無法在client
對象中“注入” options
,因此我必須在代碼中處理client
和options
對象,並在options
列表中搜索與我正在使用的合同相對應的options
。
有沒有辦法用第二次請求的值來完成Hibernate對象(在我的例子中是客戶端)?
謝謝你的幫助。
PS:問不清楚,我是法國人:)
<rant>
我一般恨冬眠,因為它是這樣一個浪費時間,也似乎運行數百個查詢的時候,如果你手工編寫的SQL會只能運行少數<\\rant>
如果被迫使用休眠模式,我可能會使用3個類似的查詢
from Options as o join fetch o.contract as co join fetch co.client as cl where cl = :client
from Contracts as co join fetch co.client as cl where cl = :client
from Client where clientId = :clientId
然后,將它們全部放入適當的Map<Long, List>
映射中,並在Java中進行聯接。
第一:您有多少數據導致第一個查詢不起作用? 如果結果有這么多行,並且您想優化此查詢,請檢查是否確實需要從db獲取的所有數據。 也許您應該對更平坦的其他對象進行投影。
如果您不使用Java處理數據,而僅將其傳遞給前端,請考慮分頁結果。
使用Hibernate的好處是ORM。 您可以將課程設置為實體。 因此,您不再需要擔心簡單的查詢。 只需使用JPA即可完成該任務。 實體看起來像這樣:
@Entity
public class Client implements Serializable {
private Long id;
private ArrayList<Contract> contracts;
// more attributes here
@Id @GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
@OneToMany
public ArrayList<Contract> getContracts() {
return contracts;
}
public void setId(Long id) {
this.id = id;
}
public void setContracts(ArrayList<Contract> contracts) {
this.contracts = contracts;
}
}
@Entity
public class Contract implements Serializable {
private Long id;
private List<Option> options;
// more attributes here
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
@OneToMany
public List<Option> getOptions() {
return options;
}
public void setId(Long id) {
this.id = id;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
等等...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.