避免JDBC调用

时间:2011-05-16 14:43:43

标签: java performance hibernate jdbc

场景是这样的:

for loop // runs say 200000 times
{
    // here, i do a select from a database, fetching few rows which are expected to increase with every new iteration of for loop
    // currently i am doing this select using simple JDBC call (using JDBC only is NOT a requirement)

    // then i do some string matching stuff and then i either insert or update a particular row (in 95% cases i will insert)
    // this insert or update is being done using Hibernate (using Hibernate over here is a requirement)
}

所以问题是,在每个循环中,我必须考虑每个先前插入/更新的行。由于这个要求,我必须在每个循环中进行JDBC调用。这个JDBC调用占用了最多的时间,降低了性能。

我想知道,是否有任何方法可以在每次迭代中使用我不需要进行JDBC调用,但是我仍然能够考虑所有记录,包括前一次插入/更新中的记录?像缓存或某些内存数据结构或类似的东西?

以下是代码:

for loop // runs say 2000 times
{
    String query = pdi.selectAllPatients(patientInfo);
    Statement st = conn.createStatement();
    ResultSet patientRs = st.executeQuery(query);

    while (patientRs.hasNext())
    {
        // some string ops
    }

    // Create session for DB No.2
    Session sessionEmpi = sessionFactoryEmpi.getCurrentSession();
    sessionEmpi.beginTransaction();

    if(some condition)
        patientDao.insertPatient(patientInfo, sessionEmpi);
    else
        patientDao.insertref(patientInfo.getref(), sessionEmpi);

    conn.commit();
}

public int insertPatient(PatientInfo input, Session session) throws SQLException {

    try {

        session.save(input.getPatient());
        session.flush();
        session.save(input.getref());
        session.getTransaction().commit();

        return 1;

    } catch (Exception ex) {
        session.getTransaction().rollback();
        ex.printStackTrace();
        return 0;
    }
}

2 个答案:

答案 0 :(得分:0)

SELECT的性能是否一致?除非您的数据相当小,否则您可能无法缓存内存中的所有更改。您也可以批量处理SELECT,有效地展开循环。

答案 1 :(得分:0)

您可以使用PreparedStatement接口而不是Statement接口,因为它可以避免不必要的调用将查询触发到数据库,您只需要将数据绑定到for循环中,这将有助于您提高性能!!

示例:

PreparedStatement s =con.prepareStatement("select * from student_master where stu_id = ?");

for()
{
   s.setString(1,"s002");
   ResultSet rs = s.executeQuery();
}