微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我试图在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");
    }
最佳答案
取自这里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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐