加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:25:16 所属栏目:大数据 来源:网络整理
导读:我试图在MySQL表中插入一行并获取它的插入ID.我知道MySQL的last_insert_id()函数,我似乎无法让它工作.目前,我正在尝试使用注释为事务的函数,我只返回0.我使用的是Spring 3.1. @Transactional (propagation = Propagation.REQUIRED,rollbackFor = Exception.c

我试图在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读