java - Spring JdbcTemplate 无法从 MySQL 获取插入 ID

标签 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");
    }

最佳答案

使用 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());

关于java - Spring JdbcTemplate 无法从 MySQL 获取插入 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9350867/

相关文章:

sql - 在 SQL Server 中执行时捕获对象依赖关系

mysql - 维护 MySQL 数据库表中元素的顺序或在 MySQL 的特定位置插入新行

Mysql - 将字符串与另一个 sql 结果连接起来

java - 访问导入的js文件中的Spring MVC模型数据

java - 如何从相对布局中提取文本并将其存储在 ArrayList 中

java - 使用 Jackson 和 Hibernate 的多对多无限递归

mysql - 如何查询某个字段比另一个字段大x天的记录?

mysql - SQL join with count 不工作

java - Wildfly activemq 集成 - 消息子系统

Java Jetty WebSocket 服务器 : Handle broadcasts with asynchronously disconnecting clients