2016-11-16 81 views
0

我有對象碩士位置和MasterCountries春天JPARepository不懶還是渴望

MasterLocation.java

@Entity 
@Table(name = "master_location", schema = "public", catalog = "master_db") 
@NamedEntityGraphs({ 
     @NamedEntityGraph(name = "MasterLocation.joinsWithMasterCountries",attributeNodes = { 
       @NamedAttributeNode("masterCountriesByCountryCode") 
     }), 
     @NamedEntityGraph(name = "MasterLocation.noJoins",attributeNodes = {}) 
}) 
public class MasterLocation { 
    private String locationCode; 
    private String locationName; 
    private String countryCode; 
    private Integer agencyCode; 
    private String port; 
    private String place; 
    private String userId; 
    private Timestamp dateCreated; 
    private Timestamp lastModified; 
    private String portRefFrom; 
    private String portRefTo; 
    private String valid; 
    private String regionCode; 
    private String bookingRef; 

    private MasterCountries masterCountriesByCountryCode; 
    @ManyToOne(fetch = FetchType.LAZY) 
    @NotFound(action = NotFoundAction.IGNORE) 
    @JoinColumn(referencedColumnName = "iso_3166_1_alpha_2_code", name = "country_Code") 
    public MasterCountries getMasterCountriesByCountryCode() { 
     return masterCountriesByCountryCode; 
    } 
} 

MasterLocationRepository.java

@Repository 
public interface MasterLocationRepository extends JpaRepository<MasterLocation, Integer> { 

    @EntityGraph(value = "MasterLocation.noJoins",type = EntityGraph.EntityGraphType.LOAD) 
    Page<MasterLocation> findByLocationNameLikeIgnoreCase(String locationName, Pageable pageable); 
} 

爲什麼對象MasterCountries仍然加載findByLocationNameLikeIgnoreCase?如何禁用在此資源庫中獲取MasterCountries?

謝謝

+0

這是你的實際嗎? 「@ Id」在哪裏?還應該有更多的獲得者...請添加完整的實體不是一個片段。 –

回答

0

我想你正在使用Hibernate作爲你的JPA提供者。默認情況下,所有單個屬性都會被急切地加載,即使是一對一或多對一的註釋爲Lazy的關係。

爲了能夠延遲加載單個屬性,您必須使用hibernate的字節碼擴展支持。在this Vlad Mihalcea's post中,你會發現如何使用Maven激活它。你剛纔下面的插件添加到您的的pom.xml文件:

<plugin> 
    <groupId>org.hibernate.orm.tooling</groupId> 
    <artifactId>hibernate-enhance-maven-plugin</artifactId> 
    <version>${hibernate.version}</version> 
    <executions> 
     <execution> 
      <configuration> 
       <enableLazyInitialization>true</enableLazyInitialization> 
      </configuration> 
      <goals> 
       <goal>enhance</goal> 
      </goals> 
     </execution> 
    </executions> 
</plugin> 

也可以嘗試改變@EntityGraph註釋類型參數來取指令,而不是LOAD,或註釋與FetchType.LAZY的masterCountriesByCountryCode。使用您當前的配置(EntityGraphType.LOAD),未包含在EntityGraph定義中的屬性將保留其默認的FETCH/LOAD配置。看看here瞭解更多詳情

another post Vlad再次談到字節碼擴展並提供了另一種選擇:子實體。我自己並沒有嘗試過子實體選項,所以我不能告訴你它的工作效果如何。

最後,另一個需要更多工作,但我認爲是最好的選擇是使用投影DTO僅選擇每種情況下需要的數據。