Reputation: 316
We are using Hibernate 3.2 and cannot upgrade due to dependency on other libraries being used in legacy applications. Currently, "native" id generator is being used in hibernate mapping file for table. In turn, hibernate uses "sequence" for Oracle and "Auto_Increment column" for MySQL. As application generates lot of Ids so in case of Oracle, to fetch next sequence lot of queries flows between database and application impacting performance. We would like to use HiLow for Oracle and would like to continue to use "Auto_Increment column" for MySQL.
Question is, How shall we define mapping file so as Hibernate should use HiLow if underlying database is Oracle and "Auto_Increment column" if underlying database is MySQL? If we cann't achieve this via mapping file, which class shall we override?
Upvotes: 2
Views: 1280
Reputation: 316
We have extended Oracle10gDialect and overridden method "supportsSequences()" to return false. This way mapping file continued to use native id generator and as configured Oracle dialect returns false for supporting sequences, Hibernate uses "TableHiLoGenerator".
Upvotes: 0
Reputation: 874
Hibernate Core provides various built-in Simple primary key generator classes, as for:
1) hilo ==> org.hibernate.id.TableHiloGenerator
2) increment ==> org.hibernate.id.IncrementGenerator, etc.
For example, lets say you have a Customer class as shown :
Customer.java
package org.myapps;
public class Customer {
private long cid; // your primary key property
...
// setters and getters
}
Now, You can Instruct hibernate Id generator to generate id's using the hilo algorithm as: Customer.hbm.xml
<hibernate-mapping>
<class name="org.myapps.Customer" table="CUSTOMER">
<id name="cid" type="int">
<column name="CID" />
<generator class="hilo">
<param name="table">hi_value</param>
<param name="column">next_value</param>
<param name="max_lo">1000</param>
</generator>
</id>
....
</hibernate-mapping>
And to use increment generator
<hibernate-mapping>
<class name="org.myapps.Customer" table="CUSTOMER">
<id name="cid" type="int">
<column name="CID" />
<generator class="increment" />
</id>
....
</hibernate-mapping>
Now, If your question is How to switch between these two generation types depending on your underlying database (Oracle Or MySQL), then in my view you need to define two hibernate configuration files :
1) oracle_hibernate.cfg.xml - for Oracle
2) mysql_hibernate.cfg.xml - for MySQL
along with two versions of hibernate mapping files for each entity:
one for Oracle (oracle_Customer.hbm.xml) using the hilo generator and
one for MySQL (mysql_Customer.hbm.xml) using the increment generator
and map these mapping files with their corresponding xxx.cfg.xml file.
Also you will need to define two utility methods to load these configuration for you depending on your Database.
NOTE : This is what i came up with, however, expert citation is deemed here and you should consult someone with more experience.
Upvotes: 1