Hibernate自定义sql获取最后一个插入ID

时间:2015-09-28 20:45:20

标签: java mysql hibernate

如何使用自定义sql和值对象方法(不保存/更新等)返回新插入行的自动生成ID。 Id(身份字段)由数据库服务器处理。

Java代码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;
}

使用DatabaseObject

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

1 个答案:

答案 0 :(得分:1)

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

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

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

    txn.commit();
    session.close();

    return result;
}