【发布时间】:2015-07-01 02:04:27
【问题描述】:
在我的 Java 应用程序中,我使用的是 SQL server and Hibernate3 with EJB。当我尝试执行选择查询with In clause 时,DB 服务器 CPU 使用率达到 100%。但是当我尝试在SQL management studio 中运行相同的查询时,查询运行时没有任何 CPU 峰值。应用服务器和数据库服务器是两台不同的机器。我的表具有以下架构,
CREATE TABLE student_table (
Student_Id BIGINT NOT NULL IDENTITY
, Class_Id BIGINT NOT NULL
, Student_First_Name VARCHAR(100) NOT NULL
, Student_Last_Name VARCHAR(100)
, Roll_No VARCHAR(100) NOT NULL
, PRIMARY KEY (Student_Id)
, CONSTRAINT UK_StudentUnique_1 UNIQUE (Class_Id, Roll_No)
);
该表包含大约 1000k 条记录。我的查询是
select Student_Id from student_table where Roll_No in ('A101','A102','A103',.....'A250');
In 子句包含 250 个值,当我尝试在 SQL 管理工作室中运行上述查询时,结果会在 1 秒内检索到,并且没有任何 CPU 峰值。但是当我尝试通过休眠运行相同的查询时,CPU 峰值达到 100% 大约 60 秒,结果在 60 秒左右检索到。休眠查询是,
Criteria studentCriteria = session.createCriteria(StudentTO.class);
studentCriteria.add(Restrictions.in("rollNo", rollNoLists)); //rollNoLists is an Arraylist contains 250 Strings
studentCriteria.setProjection(Projections.projectionList().add(Projections.property("studentId")));
List<Long> studentIds = new ArrayList<Long>();
List<Long> results = (ArrayList<Long>) studentCriteria.list();
if (results != null && results.size() > 0) {
studentIds.addAll(results);
}
return studentIds;
这是什么问题。如果通过 Management Studio 运行相同的查询,则检索结果时不会出现任何峰值,并且会在 1 秒内检索结果。有什么解决办法???
编辑1: 我的休眠生成查询是,
select this_.Student_Id as y0_ from student_table this_ where this_.Roll_No in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
编辑2: 我的执行计划 这是在索引 roll_no 之后
CREATE INDEX i_student_roll_no ON student_table (Roll_No)
,
【问题讨论】:
-
请贴一下hibernate生成的SQL查询好吗?
-
@Amogh 更新了休眠生成的查询
-
您是否尝试过用 HQL 替换条件?
-
是的,当然试过了..但没有用...同样的问题,100% CPU 使用率飙升
-
我遇到了类似的问题...我通过创建一个临时表来解决它,该表具有原始表(PK)和搜索字段(不是 PK)作为 PK,然后针对这个临时表。在 Hibernate(使用 Native SQL)下执行需要 20-30 秒的查询开始立即运行。所以我相信你应该试一试。
标签: java sql-server performance hibernate ejb