使用获取模式进行延迟提取选择不进行N + 1选择

时间:2015-09-23 14:30:05

标签: java hibernate

我正在尝试使用Lazy Fetch和Fetch模式作为Select来复制N + 1问题。我创建的测试程序只运行2个查询。在Hibernate 5.0.1中有什么变化?谷歌搜索但找不到任何相关信息也不知道我的测试用例是否正确

这是模型类中的一小段代码

@Embedded
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "Person_Education", joinColumns = { @JoinColumn(nullable = false, name = "per_edu_id") })
@GenericGenerator(name = "gen_gene", strategy = "native")
@CollectionId(columns = { @Column(name = "edu_id") }, generator = "gen_gene", type = @Type(type = "long") )
@Fetch(FetchMode.SELECT)
private List<ModelEducation> ModelEdu = new ArrayList<>();

这里是检查N + 1选择的实用方法

public class TestUtilGet {
public static void main(String[] args) {
    Session session = HibernateUtil.getSession();
    Criteria criteria = session.createCriteria(ModelPerson.class);
    List<ModelPerson> mList = criteria.list();
    for (ModelPerson mPerson : mList) {
        System.out.println("-------------------"+mPerson.getFirstName() + " " + mPerson.getLastName() + " " + mPerson.getAge()+"--------");
        List<ModelEducation> mEdu = mPerson.getModelEdu();
        for (ModelEducation mEducation : mEdu) {
            System.out.println(mEducation.getCourse()+" "+mEducation.getGrade()+" "+mEducation.getYear());
        }
    }
}
}

这是输出中的两个选择

Hibernate: 
    /* criteria query */ select
        this_.person_id as person_id1_1_0_,
        this_.age_id as age_id2_1_0_,
        this_.currentDate as currentDate3_1_0_,
        this_.firstName as firstName4_1_0_,
        this_.last_name as last_name5_1_0_,
        this_.versionId as versionId6_1_0_ 
    from
        Person this_

Hibernate: 
    /* load collection com.likki.hibernate.ModelPerson.ModelEdu */ select
        modeledu0_.per_edu_id as per_edu_id1_2_0_,
        modeledu0_.course as course2_2_0_,
        modeledu0_.grade as grade3_2_0_,
        modeledu0_.year as year4_2_0_,
        modeledu0_.edu_id as edu_id5_0_ 
    from
        Person_Education modeledu0_ 
    where
        modeledu0_.per_edu_id in (
            ?, ?, ?
        )

PERSON_EDUCATION表中有150条记录,所以我期待1 + 150选择,但只能看到2个选择。如果它有任何区别,ModelEducation类不是实体类,它用@Embeddable

注释

0 个答案:

没有答案