最后在Java Hibernate中插入了Id

时间:2015-11-27 06:24:43

标签: java hibernate postgresql jdbc

我们如何获得最后插入的值?下面是我插入值的函数。但我想获取最后插入的Id,它是自动递增的。我正在使用PostgreSQL

@Override
public int executeInsertSQLSelect(String sqlQuery) throws HibernateException {

    SQLQuery query = getCurrentSession().createSQLQuery(sqlQuery);

    logger.debug("SQL query to be executed is : " + query);

    int noOfRecordsUpdatedOrDeleted;

    try {
        noOfRecordsUpdatedOrDeleted = query.executeUpdate();


    } catch (HibernateException hbExp) {
        logger.error(String.format(
                "Error occured while executing query without Scalar"
                        + " mapping - %s ", query.getQueryString()), hbExp);
        throw hbExp;
    }
    return noOfRecordsUpdatedOrDeleted;
}

1 个答案:

答案 0 :(得分:0)

如果您使用的是ms sql server,那么您可以使用OUTPUT

例如

String sqlQuery=insert into employee(employeeName) output values('john')
SQLQuery query = getCurrentSession().createSQLQuery(sqlQuery);
query.getSingleResult()