I am developing an application using Hibernate, Derby, and Java 6. I have a database table that contains about 2.5 million records and I have a query that uses the combination of two fields to retrieve a record from this table.
Therefore, I have defined an index on these two fields in order to speed up queries. My Hibernate mapping file looks as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="...">
<class name="MyRecord" table="MYTABLE">
<id column="id" name="id" type="long">
<generator class="native"/>
</id>
<property column="myIndex" index="MY_IDX" name="myIndex" not-null="true" type="long"/>
<property column="myCode" index="MY_IDX" length="2" name="myCode" not-null="true" type="string"/>
<!-- More properties here -->
<many-to-one ... />
</class>
</hibernate-mapping>
(Note that myIndex is just the name of a field, whereas the defined daabase index is MY_IDX.)
I then execute the query as follows:
...
Session session = ...;
Criteria criteria = session.createCriteria(MyRecord.class);
criteria.add(Restrictions.eq("myIndex", myIndex));
criteria.add(Restrictions.eq("myCode", myCode));
List result = criteria.list();
...
The above query finds the correct result (one record, if present) but in my opinion it takes way too long (between 9 and 13 seconds): I do not know the details of how Hibernate manages database indexes, but I would expect a query on an indexed key to run quite fast. So even with 2.5 million records, the running time of the query should be IMO much smaller.
Question: can it be that I have configured my database index incorrectly and that no index is used at all? Or if an index has been created in the database, am I doing something wrong in my query?
UPDATE
I think that Hibernate had not created any index at all. I have created the index in Derby directly (connected to it via SQuirrel) and executed the above query again: it is now very fast (7 milliseconds). I am a bit confused: either the index attribute in the Hibernate mapping file has no use at all, or I am doing something wrong.