更新:
我理解我的问题的解决方案是进行子查询,每次应用不同的过滤器,并且它们具有减少的结果集。但我无法在MyBatis逻辑中找到一种方法。这是我的查询代码
List<IstanzaMetadato> res = null;
SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory().openSession(true);
try {
IstanzaMetadatoMapper mapper = sqlSession.getMapper(IstanzaMetadatoMapper.class);
IstanzaMetadatoExample example = new IstanzaMetadatoExample();
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
example.createCriteria().andIdMetadatoEqualTo(entry.getKey()).andValoreEqualTo(entry.getValue());
}
example.setDistinct(true);
res = mapper.selectByExample(example);
我需要在while循环中执行一个新的selectByExample,并且它必须查询previus“SELECTED”结果....
有解决方案吗?
原始问题:
我有这个表结构
我必须从表中选择具有不同过滤器的行,由最终用户指定。 这些过滤器由一对夫妇(id_metadato,valore)指定,例如,你可以拥有id_metadato = 3和valore =“pippo”;
用户可以在网页中指定0-n个过滤器,在搜索框内键入0-n值,这些值基于id_metadato
很明显,用户指定的过滤器越多,最终查询的限制就越多。
在示例中,如果用户仅填充第一个搜索框,则查询将只有一个过滤器,并且将提供将具有用户指定的对(id_metadato,valore)的所有行。 如果他使用两个搜索框,那么查询将有2个过滤器,并且在“第一个子查询”完成后,它将提供验证第一个条件和第二个条件的所有行。
我需要以最有效的方式做到这一点。我不能简单地在我的查询中添加AND子句,他们每次都必须过滤和减少结果集 我不能有效地做0-n子查询(从* IN(选择*从...)中选择*)。
有更优雅的方式吗?我正在阅读MyBatis的动态SQL查询教程,但我不确定这是正确的方法。我仍在试图找出resosultio的逻辑,然后我将尝试用MyBatis实现。
感谢您的回答
答案 0 :(得分:0)
MyBatis简化了这个嵌套子查询的过程,它足以连接过滤器标准并添加
代码的摘录如下
try {
IstanzaMetadatoMapper mapper = sqlSession.getMapper(IstanzaMetadatoMapper.class);
IstanzaMetadatoExample example = new IstanzaMetadatoExample();
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
if (listaIdUd.isEmpty()) {
example.createCriteria().andIdMetadatoEqualTo(entry.getKey()).andValoreEqualTo(entry.getValue());
example.setDistinct(true);
listaIdUd = mapper.selectDynamicNested(example);
continue;
}
example.clear();
example.createCriteria().andIdMetadatoEqualTo(entry.getKey()).andValoreEqualTo(entry.getValue()).andIdUdIn(listaIdUd);
example.setDistinct(true);
listaIdUd = mapper.selectDynamicNested(example);
}