2017-05-30 52 views
0

我在Spring Data JPA中遇到了一些簡單查詢的性能問題。Spring Data JPA - 使用ElementCollection進行查詢 - 性能低下

型號:

@Entity 
public class LogEntry { 
    .. 
    @NotNull 
    @ElementCollection(fetch = FetchType.EAGER) 
    private List<String> parameters; 

    @ManyToOne 
    private Guest guest; 
    .. 
} 

庫:

Page<LogEntry> findByGuestOrderByCreationDateDesc(Guest guest, Pageable pageable); 

我想顯示的所有參數的日誌條目列表。但查詢速度非常慢。找到所有條目後,它開始查詢每個條目的參數。

日誌顯示大量的這些行:

Hibernate: select parameters0_.LogEntry_id as LogEntry1_8_0_, parameters0_.parameters as paramete2_9_0_ from LogEntry_parameters parameters0_ where parameters0_.LogEntry_id=? 

我正在尋找,以提高查詢的方式。我嘗試使用聯合抓取而沒有成功。

@Query("select l from LogEntry l join fetch l.parameters where l.guest = ?1 order by l.creationDate desc") 


Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,collection join,fetch join,fetch non-lazy properties,classAlias=null,role=domain.guest.LogEntry.parameters,tableName={none},tableAlias=parameters1_,origin=null,columns={,className=null}}] [select count(l) from domain.guest.LogEntry l join fetch l.parameters where l.guest = ?1] 
+1

問題不在於您提供的查詢。這是Spring從查詢中派生出來的count查詢。 AFAIR,你可以在Query註釋中指定一個countQuery(它不會對連接獲取(這應該是一個左連接fetc,BTW))。 http://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/Query.html#countQuery-- –

回答

0

您可以嘗試下面的代碼。

@Query("select logEntry from LogEntry logEntry join fetch logEntry.parameters as params join fetch logEntry.guest as guest where guest.id = :guestId order by logEntry.creationDate desc") 
Page<LogEntry> findByGuestOrderByCreationDateDesc(@Param Long guestId, Pageable pageable); 
+0

我仍然得到這個錯誤:引起:java .lang.IllegalArgumentException:org.hibernate.QueryException:查詢指定的連接讀取,但獲取的關聯的所有者不在選擇列表中[FromElement {顯式,集合連接,讀取連接,讀取非懶惰屬性,classAlias = params ,role = domain.guest.LogEntry.parameters,tableName = {none},tableAlias = parameters1_,origin = null,columns = {,className = null}}] [select count(logEntry)from domain.guest.LogEntry logEntry join fetch作爲參數的logEntry.parameters加入獲取logEntry.guest作爲guest,其中guest.id =:guestId] – NoobieNoob

+0

我認爲,您嘗試的查詢可能無法正常工作。因爲你已經添加了count(logEntry)。從domain.guest.LogEntry中選擇count(logEntry)logEntry以guest參數的形式訪問獲取logEntry.parameters,其中guest.id =:guestId。這可以使用本機查詢來修復。你可以請指定這些表的名稱。所以我可以幫你編寫查詢。 – Sudhakar

相關問題