2017-05-30 514 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