如何在语句末尾添加返回findSingleOrNoItem()
以在getClassName()
语句中显示for循环计数器getAbsolutePercentage()
和findSingleOrNoItem()
?我添加了一个计数器的原因,有些会有getClassName()
和getAbsolutePercentage()
的4个值,有些会有6个值吗?所以这将取决于在setParameter 1上传递的cosModel。
@Override
public TrafficProfile getTrafficProfileByCosClassAllocationNew(CosModel cosModel, Direction direction,
List<ClassOfServiceAllocation> cosClassAllocation, RouterType routerType) throws Exception {
EntityManager em = getEntityManager();
logger.info("Starting getTrafficProfileByCosClass2Allocations cos2 " );
Query query = em.createNativeQuery(buildTrafficProfileByCosClassAllocationQueryNew(cosModel, direction, cosClassAllocation, routerType), TrafficProfile.class);
query.setParameter(1, cosModel.name());
query.setParameter(2, direction.name());
int i= 2;
for(ClassOfServiceAllocation alloc : cosClassAllocation){
query.setParameter(i++, alloc.getClassName());
query.setParameter(i++, alloc.getAbsolutePercentage());
}
return findSingleOrNoItem(query, "Traffic_Profile", "cos_model = " + cosModel.name() + ", direction = " + direction.name() + ?;
}
我正在遵循以下现有代码,但这仅适用于cos6。我将同时拥有cos4和cos6,因此我无法进行硬编码。
@Override
public TrafficProfile getTrafficProfileByCosClassAllocations(Direction direction,
ClassOfService6Allocations cosClassAllocation, RouterType routerType) throws Exception {
EntityManager em = getEntityManager();
logger.info("Starting getTrafficProfileByCosClass6Allocations cos6" );
Query query = em.createNativeQuery(buildTrafficProfileByCosClassAllocationsQuery(direction, cosClassAllocation, routerType), TrafficProfile.class);
query.setParameter(1, "cos6");
query.setParameter(2, direction.name());
query.setParameter(3, cosClassAllocation.getCos1());
query.setParameter(4, cosClassAllocation.getCos2V());
query.setParameter(5, cosClassAllocation.getCos2());
query.setParameter(6, cosClassAllocation.getCos3());
query.setParameter(7, cosClassAllocation.getCos4());
query.setParameter(8, cosClassAllocation.getCos5());
return findSingleOrNoItem(query, "Traffic_Profile", "cos_model = cos6, direction = " + direction.name() + " cos1 = " + cosClassAllocation.getCos1()
+ " cos2v = " + cosClassAllocation.getCos2V() + " cos2 = " + cosClassAllocation.getCos2()
+ " cos3 = " + cosClassAllocation.getCos3() + " cos4 = " + cosClassAllocation.getCos4() + " cos5 = " + cosClassAllocation.getCos5() );
}
答案 0 :(得分:0)
假设您的ClassOfService6Allocations
和ClassOfService4Allocations
继承自ClassOfServiceAllocation
,您可以在for循环中检查当前对象的类型,然后转换为此类,例如:
for(ClassOfServiceAllocation alloc : cosClassAllocation) {
if (alloc instanceof ClassOfService6Allocations) {
ClassOfService6Allocations alloc6 = (ClassOfService6Allocations) alloc;
//set your parameters using the alloc6 object
} else if (alloc instanceof ClassOfService4Allocations) {
ClassOfService4Allocations alloc4 = (ClassOfService4Allocations) alloc;
//set your parameters using the alloc4 object
}