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?