Spring JdbcTemplate无法从MySQL获取插入ID

时间:2012-02-19 16:21:52

标签: java mysql sql spring

我正在尝试在MySQL表中插入一行并获取它的插入ID。我知道MySQL last_insert_id()函数,我似乎无法让它工作。目前,我正在尝试使用注释为事务的函数,我只返回0。我使用的是Spring 3.1。

    @Transactional (propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private long insertTransactionRecord 
    (
        int custID, 
        int porID, 
        String date, 
        short crvID
    ) {
        m_template.update ("INSERT INTO " +
                           "    transaction " +
                           "( " +
                           "    por_id, " +
                           "    cust_id, " +
                           "    trans_date, " +
                           "    crv_id " +
                           ") " +
                           "VALUES " +
                           "( " +
                           "    ?, " +
                           "    ?, " +
                           "    ?, " +
                           "    ? " +
                           ")",
                           new Object[] {
                               porID,
                               custID,
                               date,
                               crvID
                           });
        return m_template.queryForLong ("SELECT " +
                                        "    last_insert_id() " +
                                        "FROM " +
                                        "    transaction " +
                                        "LIMIT 1");
    }

3 个答案:

答案 0 :(得分:9)

使用Spring的内置支持,而不是自己动手。

SqlUpdate insert = new SqlUpdate(ds, "INSERT INTO company (name) VALUES (?)");
insert.declareParameter(new SqlParameter(Types.VARCHAR)); 
insert.setReturnGeneratedKeys(true);
// assuming auto-generated col is named 'id'
insert.setGeneratedKeysColumnNames(new String[] {"id"}); 
insert.compile();
....
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
insert.update(new Object[]{"test"}, keyHolder);
System.out.println(keyHolder.getKey().longValue());

答案 1 :(得分:8)

取自http://www.codefutures.com/spring-dao/

public int createCompany(Company company) throws SQLException {
        jdbcTemplate.update(
                "INSERT INTO company (name) VALUES (?)",
                company.getName()
        );
        return jdbcTemplate.queryForInt( "select last_insert_id()" );
    }

如果你注意到那里没有FROM

答案 2 :(得分:1)

The documentation显示获取最后一个插入ID的语法是:

SELECT LAST_INSERT_ID()