jpql多表关联查询

时间:2022-09-22 09:50:31

a表关联b表,b表关联c表,c表关联d表时,直接按照query对象的属性进行多级关联可能会有问题,如关联对象为null,如下所示,为发生错误情况:

public @Test void query() {
	QContractInnerloanInterest q = QContractInnerloanInterest.contractInnerloanInterest;
	QContractInnerloanMain loadMain = q.contractInnerloanMain;
	QContractProjectInfo projectInfo = loadMain.contractProjectInfo;
	QInterfaceProjectInfo interProjectInfo = projectInfo.interfaceProjectInfo;
	log.info(interProjectInfo.toString());//空指针报错
}

因此需要按照如下方式关联

private JPQLQuery<MDClass> getBasicQuery(){
	QMDClass qClass = QMDClass.mDClass;
	QMDComponent t = QMDComponent.mDComponent;
	QMDModule m = QMDModule.mDModule;
	return repository.createDslQuery()
		.select(qClass).from(qClass)
		.innerJoin(qClass.component, t).fetchJoin()
		.innerJoin(t.module, m).fetchJoin();
}
public MDClass[] findAllMDClassForCache() {
	QMDClass qClass = QMDClass.mDClass;
	JPQLQuery<MDClass> query = getBasicQuery()
		.orderBy(qClass.isMainClass.desc().nullsLast()).orderBy(qClass.seq.asc());
	return CommonMethods.toArray(query.fetch());
}