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

前端之家收集整理的这篇文章主要介绍了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

原文链接:https://www.f2er.com/spring/431988.html

猜你在找的Spring相关文章