user2727195 user2727195 - 7 months ago 155
Java Question

Hibernate custom sql to get last insert id

how can I return auto-generate id of a newly inserted row using custom sql and value object method (without save/update etc.). Id's (Identity Fields) are handled by the database server.

Java code DatabaseObject.java

public int insert(String sql, Object valueObject) throws Exception {
Session session = Entitlement.getSessionFactory().openSession();
session.beginTransaction();
int result = session.createSQLQuery(sql)
.setProperties(valueObject).executeUpdate();
session.getTransaction().commit();
session.close();
return result;
}


Using DatabaseObject

String sql = "INSERT INTO user(emailAddress, password) VALUES(:emailAddress, :password)";
UserVO valueObject = new UserVO("test@email.com", "pass1234");
databaseObject.insert(sql, valueObject);

Answer
public BigInteger insert(String sql, Object valueObject) throws Exception
{
    Session session = Entitlement.getSessionFactory().openSession();
    session.beginTransaction();

    session.createSQLQuery(sql)
           .setProperties(valueObject)
           .executeUpdate();

    BigInteger result = session.createSQLQuery("SELECT LAST_INSERT_ID()")
                               .uniqueResult();

    session.getTransaction().commit();
    session.close();

    return result;
}