我在hibernate中有一个投影问题,完成一个简单的查询需要永远。 我的道法:
@Override @Transactional public List<String> getSourcePaths(List<Integer> sourceIds) { @SuppressWarnings("unchecked") List<String> list = getSession() .createCriteria(AnaFileDB.class) .setProjection(Projections.property("sourcePath")) .add(Restrictions.in("source.id", sourceIds)) .list(); return list; }
AnaFileDB类是这样的:
@Entity @Table(name = "ANA_FILE") public class AnaFileDB { ... private String sourcePath; private AnaFileSourceDB source; ... }
日志:
2014-01-15 17:31:36,227 [http-8080-5] DEBUG org.hibernate.jdbc.AbstractBatcher - 即将打开PreparedStatement(打开PreparedStatements:0,全局:0)
休眠:
/ *条件查询* /选择
this_.FILE_SOURCE_PATH为y0_
从
ANA_FILE this_
其中
()中的this_.FILE_SOURCE_ID ?
)
2014-01-15 17:31:36,227 [http-8080-5] TRACE org.hibernate.type.IntegerType - 将'2'绑定到参数:1
2014-01-15 18:17:43,469 [http-8080-5] DEBUG org.hibernate.jdbc.AbstractBatcher - 即将打开ResultSet(打开ResultSet:0,全局:0)
2014-01-15 18:17:43,569 [http-8080-5] DEBUG org.hibernate.loader.Loader - 结果行:
2014-01-15 18:17:43,569 [http-8080-5] TRACE org.hibernate.type.StringType - 将'2013.03.01_Tom Januario / 01_CTG1203401_CTG.csv'作为列返回:y0_
2014-01-15 18:17:43,470 [http-8080-5] DEBUG org.hibernate.loader.Loader - 结果行:
2014-01-15 18:17:43,470 [http-8080-5] TRACE org.hibernate.type.StringType - 将'2013.03.01_Tom Januario / 02_CTG2203539_CTG.csv'作为列返回:y0_
2014-01-15 18:17:43,470 [http-8080-5] DEBUG org.hibernate.loader.Loader - 结果行:
2014-01-15 18:17:43,470 [http-8080-5] TRACE org.hibernate.type.StringType - 将'2013.03.01_Tom Januario / 03_CTG3203718_CTG.csv'作为列返回:y0_
因为有很多行(成千上万),所以我得到了像这样的日志文件
2014-01-15 17:13:40,462 [http-8080-1] DEBUG org.hibernate.loader.Loader - 结果行:
2014-01-15 17:13:40,462 [http-8080-1] TRACE org.hibernate.type.StringType - 将'project2 / screen4 / run4 / CTG / CSI000000447_CTG.csv'作为列返回:y0 _
如何解决?
答案 0 :(得分:0)
如果你的表有大量记录,那么IN
将需要很长时间才能执行。尝试EXPLAIN
查询并在该表上添加INDEX
可能会得到一些提升
<强>更新强>
您可以尝试这种方式:
Disjunction orConditions = Restrctions.disjunction();
orConditions.add(Restrictions.in("source.id", sourceIds));
List<String> list = session.createCriteria(AnaFileDB.class)
.add(orConditions)
.list();