JPA Hibernate Lazy加载不按预期工作

时间:2013-09-26 23:49:59

标签: sql hibernate jpa spring-data-jpa

我跟随两个具有双向关系@OneToMany和@ManyToOne的实体。当我使用如下所示的连接查询查询子表时,hibernate会自动查询每个MinuteData(子表)的StandardDimension(Parent)表,以加载@ManyToOne关系,即使它被标记为延迟加载。这导致数据库性能问题。你能帮我解决一下这个问题吗?对于每个MinuteData,它都不会加载标准维度记录?我正在使用JPA 2.0和hibernate-core-4.1.1.Final。任何帮助将不胜感激。如何阻止hibernate加载StandardDimension对象?

@Query("SELECT md FROM StandardDimension sd ,MinuteData md where  sd.dimensionAK = md.dimensionFK and sd.app = :applicationId and md.timeBucket between :startTime and :endTime ")
public List<MinuteData> findMinuteDataByTimeBucket( @Param("startTime") Date startTime,     @Param("endTime") Date endTime, @Param("applicationId") String applicationId); 



@Entity (name="StandardDimension")
@Table (name="STANDARD_DIMENSION")
public class StandardDimension implements Serializable {

    @OneToMany (targetEntity=MinuteData.class, fetch=FetchType.LAZY, mappedBy="dimensionFK", cascade=CascadeType.REMOVE)
    private Set<MinuteData> muniteDateDimensionViaFK = new HashSet<MinuteData>();  
}

@Entity (name="MinuteData")
@Table (name="MINUTE_DATA")
public class MinuteData implements Serializable {
........

    @ManyToOne (fetch=FetchType.LAZY)
    @JoinColumn(name="DIMENSION_FK", referencedColumnName = "DIMENSION_AK", nullable=false , unique=false , insertable=true, updatable=true)
    private StandardDimension dimensionFK;  
.........
    }
Here is SQL Statement form console:
    Hibernate: 
        select
            minutedata1_.minute_data_pk as minute1_1_,
            minutedata1_.created_date as created2_1_,
            minutedata1_.data_obj as data3_1_,
            minutedata1_.dimension_fk as dimension6_1_,
            minutedata1_.modified_date as modified4_1_,
            minutedata1_.time_bucket as time5_1_ 
        from
            standard_dimension standarddi0_,
            minute_data minutedata1_ 
        where
            standarddi0_.dimension_ak=minutedata1_.dimension_fk 
            and standarddi0_.app=? 
            and (
                minutedata1_.time_bucket between ? and ?
            )
    Hibernate: 
        select
            standarddi0_.standard_dimensions_pk as standard1_2_0_,
            standarddi0_.app as app2_0_,
            standarddi0_.created_date as created3_2_0_,
            standarddi0_.data_center as data4_2_0_,
            standarddi0_.dimension_ak as dimension5_2_0_,
            standarddi0_.env as env2_0_,
            standarddi0_.last_seen as last7_2_0_,
            standarddi0_.modified_date as modified8_2_0_,
            standarddi0_.server as server2_0_,
            standarddi0_.app_version as app10_2_0_ 
        from
            standard_dimension standarddi0_ 
        where
            standarddi0_.dimension_ak=?

1 个答案:

答案 0 :(得分:1)

您是否100%确定没有任何内容会导致延迟加载StandardDimension? 有时它是由一个过于实现的equals或hashcode触发的。

如果没有,您是否可以使用Criteria API尝试查询,看看它是否有任何区别?