1

I am using the following code to run native sql queries on hibernate (SQLQuery) has been deprecated.

private static int executeUpdate(String sql) {
    int result = 0;
    Session session = HibernateSessionFactory.getSession();
    org.hibernate.Transaction tr = session.beginTransaction();
    NativeQuery nativeQuery = session.createNativeQuery(sql);
    int executeUpdate = nativeQuery.executeUpdate();
    tr.commit();
    return executeUpdate;
}

It all works fine but I want the same method to also return the id of the last inserted element, I want the way to be table agnostic.

[[EDIT]]

One way to do this can be to pass a native query with returning id and then use this code:

private static int executeUpdate(String sql) {
        int result = 0;
        List<HashMap<String, Object>> ret = new ArrayList<HashMap<String, Object>>();
        Session session = HibernateSessionFactory.getSession();
        org.hibernate.Transaction tr = session.beginTransaction();
        NativeQuery nativeQuery = session.createNativeQuery(sql);
        ret = nativeQuery.list();
        tr.commit();
        return Integer.parseInt(ret.get(0).get("id").toString());
    }

Can there be some other way?

absin
  • 1,116
  • 10
  • 21

1 Answers1

0

You can do that whit getSingleResult() , in your example

private static int executeUpdate(String sql) {
    int result = 0;
    Session session = HibernateSessionFactory.getSession();
    org.hibernate.Transaction tr = session.beginTransaction();
    NativeQuery nativeQuery = session.createNativeQuery(sql);

    //here I'm assuming you are getting a BigInteger as result, change accordingly
    BigInteger executeUpdate = (BigInteger) nativeQuery.getSingleResult(); 
    tr.commit();
    return executeUpdate;
}

Even if the javadoc says that getSingleResult() is used for SELECT, looks working anyway for me.

Hope this helps

Leviand
  • 2,745
  • 4
  • 29
  • 43
  • 1
    Nope fails and throws, `14:52:25.359 [main] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - No results were returned by the query.` – absin Jul 27 '18 at 09:22
  • The difference in the method's result might have something to do with the underlying SQL engine. I use PostgreSQL, and it fails in that case. Added that tag to the question. – absin Jul 27 '18 at 09:28
  • Might be, I've tried with different db without any error :( – Leviand Jul 27 '18 at 09:35
  • Undocumented features tend to behave like that :) – absin Jul 27 '18 at 15:06