Search code examples
sqlhibernateauto-increment

How to get auto-increment after executing SQLQuery.executeUpdate() insert statement


Is it possible to retrieve autoinc field after I execute my insert:

String queryString = "insert into " + String.format("table%04d", id) +
                "(sectionid, topicid, dc) values (" + entry.getSectionId() +
            ", " + entry.getTopicId() + ", " + entry.getDc() + ")";
SQLQuery query = session.createSQLQuery(queryString);
query.executeUpdate();

The table has four fields

eid - autoinc
sectionid - int
topicid - int
dc - int

Please help me


Solution

  • Unfortunately, you are bypassing much of Hibernate's database agnostic benefits, by using SQL queries instead of HQL. If you absolutely cannot use HQL, you will have to implement your own database specfic implementations. To do that, you first need to get the JDBC driver class from Hibernate:

    How to get database metadata from entity manager

    Once you have you driver class, you can do a database specific query based on that class. Since you can't modify the driver class to implement an interface with a specific get autoinc query, I recommend Nico's suggestion in the following link:

    switch instanceof?

    Once you implement a switch statement on the driver class, you can choose whether to implement a MYSQL, MSSQL, or other autoinc query.