Spring jdbcTemplate 新增数据返回主键ID

这里我直接用一个项目中的函数来做案例:


/**
   * 初始化商户出款记录
   * @param orderRequestMoney
   * @return
   */
  public void addOrderRequestMoney(final OrderRequestMoney orderRequestMoney) {
      //
      KeyHolder keyHolder = new GeneratedKeyHolder();
      getJdbcTemplate().update(new PreparedStatementCreator() {
          public PreparedStatement createPreparedStatement(Connection conn) {
              PreparedStatement ps = null;
              try {
                  ps = conn.prepareStatement(SQL_addOrderRequestMoney);
                  ps.setLong(1, orderRequestMoney.getCompanyID());
                  ps.setInt(2, orderRequestMoney.getEmailState());
              } catch (SQLException e) {
                  logger.error("addOrderRequestMoney发生Exception异常", e);
                  throw new ServiceException(e);
              }
              return ps;
          }
      }, keyHolder);
      //
      orderRequestMoney.setDealLinkID(keyHolder.getKey().intValue());
  }
  final static String SQL_addOrderRequestMoney = "insert into Order_RequestMoney(CompanyID,CreateTime,EmailState,ExprieTime) values(?,GETDATE(),?,DATEADD(HOUR, 2, GETDATE()));select @@IDENTITY as newid";


你可能感兴趣的:(id,返回主键,新增数据)