List<BeanCollection<?>> batch = loadRequest.getBatch();
int batchSize = getBatchSize(batch.size());
LoadManyBuffer ctx = loadRequest.getLoadContext();
BeanPropertyAssocMany<?> many = ctx.getBeanProperty();
PersistenceContext pc = ctx.getPersistenceContext();
ArrayList<Object> idList = new ArrayList<Object>(batchSize);
for (int i = 0; i < batch.size(); i++) {
BeanCollection<?> bc = batch.get(i);
EntityBean ownerBean = bc.getOwnerBean();
Object id = many.getParentId(ownerBean);
idList.add(id);
}
int extraIds = batchSize - batch.size();
if (extraIds > 0) {
Object firstId = idList.get(0);
for (int i = 0; i < extraIds; i++) {
idList.add(firstId);
}
}
BeanDescriptor<?> desc = ctx.getBeanDescriptor();
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(many.getTargetType());
String orderBy = many.getLazyFetchOrderBy();
if (orderBy != null) {
query.orderBy(orderBy);
}
String extraWhere = many.getExtraWhere();
if (extraWhere != null) {
// replace special ${ta} placeholder with the base table alias
// which is always t0 and add the extra where clause
String ew = StringHelper.replaceString(extraWhere, "${ta}", "t0");
query.where().raw(ew);
}
query.setLazyLoadForParents(idList, many);
many.addWhereParentIdIn(query, idList);
query.setPersistenceContext(pc);
String mode = loadRequest.isLazy() ? "+lazy" : "+query";
query.setLoadDescription(mode, loadRequest.getDescription());
// potentially changes the joins and selected properties
ctx.configureQuery(query);
if (loadRequest.isOnlyIds()) {
// override to just select the Id values
query.select(many.getTargetIdProperty());
}