Spring JdbcTemplate无法从MySQL获取插入ID

Nik*_*Nik 5 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");
    }
Run Code Online (Sandbox Code Playgroud)

pap*_*pap 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());
Run Code Online (Sandbox Code Playgroud)

  • Spring在手册中也有一个例子:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html#jdbc-auto-genereted-keys (3认同)

Ser*_*ner 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()" );
    }
Run Code Online (Sandbox Code Playgroud)

如果你注意到没有FROM出现

  • 我不认为这种方法是线程安全的,是吗?queryForInt(..)调用可能在多次插入发生后发生,并为其上方的insert语句返回错误的ID. (2认同)