读书人

关于spring jdbcTemplate获得LAST_INS

发布时间: 2012-09-01 09:33:03 作者: rapoo

关于spring jdbcTemplate取得LAST_INSERT_ID
spring的jdbctemplate提供的方案:



查看相关PreparedStatement对象的具体执行源码


回到PreparedStatement对象的executeUpdate方法
public ResultSet getGeneratedKeys()        throws SQLException    {        if(batchedGeneratedKeys == null)        {            return getGeneratedKeysInternal();        } else        {            Field fields[] = new Field[1];            fields[0] = new Field("", "GENERATED_KEY", -5, 17);            fields[0].setConnection(connection);            return new com.mysql.jdbc.ResultSet(currentCatalog, fields, new RowDataStatic(batchedGeneratedKeys), connection, this);        }    }    protected ResultSet getGeneratedKeysInternal()        throws SQLException    {        Field fields[] = new Field[1];        fields[0] = new Field("", "GENERATED_KEY", -5, 17);        fields[0].setConnection(connection);        ArrayList rowSet = new ArrayList();        long beginAt = getLastInsertID();        int numKeys = getUpdateCount();        if(results != null)        {            String serverInfo = results.getServerInfo();            if(numKeys > 0 && results.getFirstCharOfQuery() == 'R' && serverInfo != null && serverInfo.length() > 0)                numKeys = getRecordCountFromInfo(serverInfo);            if(beginAt > 0L && numKeys > 0)            {//根据更新条数会累加LastInsertID的值,因为在插入多条的时候只会默认返回第一条执行后产生的ID                for(int i = 0; i < numKeys; i++)                {                    byte row[][] = new byte[1][];                    row[0] = Long.toString(beginAt++).getBytes();                    rowSet.add(row);                }            }        }        return new com.mysql.jdbc.ResultSet(currentCatalog, fields, new RowDataStatic(rowSet), connection, this);    }

读书人网 >其他数据库

热点推荐