The fastest way to check if some records in a database table?

前端 未结 6 1450
耶瑟儿~
耶瑟儿~ 2020-12-14 22:44

I have a huge table to work with . I want to check if there are some records whose parent_id equals my passing value . currently what I implement this is by using \"select

6条回答
  •  无人及你
    2020-12-14 23:35

    select count(*) should be lighteningly fast if you have an index, and if you don't, allowing the database to abort after the first match won't help much.

    But since you asked:

    boolean exists = session.createQuery("select parent_id from Entity where parent_id=?")
                            .setParameter(...)
                            .setMaxResults(1)
                            .uniqueResult() 
                     != null;
    

    (Some syntax errors to be expected, since I don't have a hibernate to test against on this computer)

    For Oracle, maxResults is translated into rownum by hibernate.

    As for what uniqueResult() does, read its JavaDoc! Using uniqueResult instead of list() has no performance impact; if I recall correctly, the implementation of uniqueResult delegates to list().

提交回复
热议问题