Java Code Examples for org.springframework.jdbc.support.GeneratedKeyHolder

The following examples show how to use org.springframework.jdbc.support.GeneratedKeyHolder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-analysis-note   Source File: SqlUpdateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testUpdateAndGeneratedKeys() throws SQLException {
	given(resultSetMetaData.getColumnCount()).willReturn(1);
	given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getObject(1)).willReturn(11);
	given(preparedStatement.executeUpdate()).willReturn(1);
	given(preparedStatement.getGeneratedKeys()).willReturn(resultSet);
	given(connection.prepareStatement(INSERT_GENERATE_KEYS,
			PreparedStatement.RETURN_GENERATED_KEYS)
		).willReturn(preparedStatement);

	GeneratedKeysUpdater pc = new GeneratedKeysUpdater();
	KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
	int rowsAffected = pc.run("rod", generatedKeyHolder);

	assertEquals(1, rowsAffected);
	assertEquals(1, generatedKeyHolder.getKeyList().size());
	assertEquals(11, generatedKeyHolder.getKey().intValue());
	verify(preparedStatement).setString(1, "rod");
	verify(resultSet).close();
}
 
Example 2
Source Project: dts   Source File: TransactionLogStorage.java    License: Apache License 2.0 6 votes vote down vote up
public void insertBranchLog(BranchLog branchLog) {
    PreparedStatementCreator psc = new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(
                "insert into dts_branch_record (trans_id,state,resource_ip,resource_info,gmt_created,gmt_modified)"
                    + " values (?,?,?,?,now(),now())",
                Statement.RETURN_GENERATED_KEYS);
            ps.setLong(1, branchLog.getTransId());
            ps.setInt(2, branchLog.getState());
            ps.setString(3, branchLog.getResourceIp());
            ps.setString(4, branchLog.getResourceInfo());
            return ps;
        }
    };
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(psc, keyHolder);
    long branchId = keyHolder.getKey().longValue();
    branchLog.setBranchId(branchId);
    branchLog.setGmtCreated(Calendar.getInstance().getTime());
    branchLog.setGmtModified(Calendar.getInstance().getTime());
}
 
Example 3
Source Project: dts   Source File: TransactionLogStorage.java    License: Apache License 2.0 6 votes vote down vote up
public void insertGlobalLog(final GlobalLog globalLog) {
    PreparedStatementCreator psc = new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(
                "insert into dts_global_record (state,client_info,client_ip,gmt_created,gmt_modified) values (?,?,?,now(),now())",
                Statement.RETURN_GENERATED_KEYS);
            ps.setInt(1, globalLog.getState());
            ps.setString(2, globalLog.getClientInfo());
            ps.setString(3, globalLog.getClientIp());
            return ps;
        }
    };
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(psc, keyHolder);
    long txId = keyHolder.getKey().longValue();
    globalLog.setTransId(txId);
    globalLog.setGmtCreated(Calendar.getInstance().getTime());
    globalLog.setGmtModified(Calendar.getInstance().getTime());
}
 
Example 4
Source Project: maven-framework-project   Source File: JdbcCalendarUserDao.java    License: MIT License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 5
/**
 * Creates the employee in the database and returns the id of the created employee.
 * @param employee the employee to be created
 * @return the id of the created employee.
 */
public long saveAndReturnId(Employee employee) {
  String sqlQuery = "insert into employees(first_name, last_name, yearly_income) " +
                    "values (?, ?, ?)";

  KeyHolder keyHolder = new GeneratedKeyHolder();

  jdbcTemplate.update(connection -> {
    PreparedStatement stmt = connection.prepareStatement(sqlQuery, new String[]{"id"});
    stmt.setString(1, employee.getFirstName());
    stmt.setString(2, employee.getLastName());
    stmt.setLong(3, employee.getYearlyIncome());
    return stmt;
  }, keyHolder);

  return keyHolder.getKey().longValue();
}
 
Example 6
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 7
private long saveTacoInfo(Taco taco) {
  taco.setCreatedAt(new Date());
  PreparedStatementCreator psc =
      new PreparedStatementCreatorFactory(
          "insert into Taco (name, createdAt) values (?, ?)",
          Types.VARCHAR, Types.TIMESTAMP
      ).newPreparedStatementCreator(
          Arrays.asList(
              taco.getName(),
              new Timestamp(taco.getCreatedAt().getTime())));

  KeyHolder keyHolder = new GeneratedKeyHolder();
  jdbc.update(psc, keyHolder);

  return keyHolder.getKey().longValue();
}
 
Example 8
Source Project: jdbctemplatetool   Source File: JdbcTemplateProxy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * insert a row with auto increament id
 * @param sql
 * @param params
 * @param autoGeneratedColumnName
 * @return
 * @throws DataAccessException
 */
public int insert(String sql,Object[] params,String autoGeneratedColumnName)
		throws DataAccessException{
	//dynamic change catalog name
	sql = changeCatalog(sql);
	
	ReturnIdPreparedStatementCreator psc = new ReturnIdPreparedStatementCreator(sql, params, autoGeneratedColumnName);
	KeyHolder keyHolder = new GeneratedKeyHolder();
	try{
		jdbcTemplate.update(psc, keyHolder);
	}catch(DataAccessException e){
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for(Object p:params){
			sb.append(p + " | ");
		}
		sb.append("]");
		logger.error("Error SQL: " + sql + " Params: " + sb.toString());
		throw e;
	}
	
	return keyHolder.getKey().intValue();
}
 
Example 9
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 10
Source Project: tcc-transaction   Source File: TradeOrderRepository.java    License: Apache License 2.0 6 votes vote down vote up
public void insert(TradeOrder tradeOrder) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement stmt = connection.prepareStatement("insert into red_trade_order(self_user_id,opposite_user_id,merchant_order_no,amount,status) values(?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
            stmt.setObject(1, tradeOrder.getSelfUserId());
            stmt.setObject(2, tradeOrder.getOppositeUserId());
            stmt.setObject(3, tradeOrder.getMerchantOrderNo());
            stmt.setObject(4, tradeOrder.getAmount());
            stmt.setObject(5, tradeOrder.getStatus());
            return stmt;
        }
    }, keyHolder);
    tradeOrder.setId(keyHolder.getKey().longValue());
}
 
Example 11
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 12
Source Project: nimble-orm   Source File: P2_InsertOp.java    License: GNU General Public License v2.0 6 votes vote down vote up
private int namedJdbcExecuteUpdateWithReturnId(Field autoIncrementField, Object t, String sql, Object... args) {
	log(sql);
	long start = System.currentTimeMillis();
	List<Object> argsList = new ArrayList<Object>(); // 不要直接用Arrays.asList,它不支持clear方法
	if(args != null) {
		argsList.addAll(Arrays.asList(args));
	}

	KeyHolder keyHolder = new GeneratedKeyHolder();

	int rows = namedParameterJdbcTemplate.update(
			NamedParameterUtils.trans(sql, argsList),
			new MapSqlParameterSource(NamedParameterUtils.transParam(argsList)),
			keyHolder); // 因为有in (?) 所以使用namedParameterJdbcTemplate

	if(rows > 0) {
		long primaryKey = keyHolder.getKey().longValue();
		DOInfoReader.setValue(autoIncrementField, t, primaryKey);
	}

	long cost = System.currentTimeMillis() - start;
	logSlow(cost, sql, argsList);
	return rows;
}
 
Example 13
Source Project: poli   Source File: JdbcDataSourceDao.java    License: MIT License 6 votes vote down vote up
public long insert(JdbcDataSource ds) {
    String rawPassword = ds.getPassword();
    String encryptedPassword = PasswordUtils.getEncryptedPassword(rawPassword);
    String sql = "INSERT INTO p_datasource(name, connection_url, driver_class_name, username, password, ping) "
                + "VALUES(:name, :connection_url, :driver_class_name, :username, :password, :ping)";
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue(JdbcDataSource.NAME, ds.getName());
    params.addValue(JdbcDataSource.CONNECTION_URL, ds.getConnectionUrl());
    params.addValue(JdbcDataSource.DRIVER_CLASS_NAME, ds.getDriverClassName());
    params.addValue(JdbcDataSource.USERNAME, ds.getUsername());
    params.addValue(JdbcDataSource.PASSWORD, encryptedPassword);
    params.addValue(JdbcDataSource.PING, ds.getPing());

    KeyHolder keyHolder = new GeneratedKeyHolder();
    npjt.update(sql, params, keyHolder, new String[] { JdbcDataSource.ID});
    return keyHolder.getKey().longValue();
}
 
Example 14
Source Project: metacat   Source File: MySqlLookupService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * findOrCreateLookupByName.
 *
 * @param name name to find or create
 * @return Look up object
 * @throws SQLException sql exception
 */
private Lookup findOrCreateLookupByName(final String name) throws SQLException {
    Lookup lookup = get(name);
    if (lookup == null) {
        final KeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            final PreparedStatement ps = connection.prepareStatement(SQL_INSERT_LOOKUP,
                Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, name);
            ps.setString(2, STRING_TYPE);
            ps.setString(3, config.getLookupServiceUserAdmin());
            ps.setString(4, config.getLookupServiceUserAdmin());
            return ps;
        }, holder);
        final Long lookupId = holder.getKey().longValue();
        lookup = new Lookup();
        lookup.setName(name);
        lookup.setId(lookupId);
    }
    return lookup;
}
 
Example 15
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 16
/**
 * Demonstrate how to insert and retrieve a generated key.
 * <p>
 * The {@code id} column of the {@code short_message} table can generated ids.
 * In order to retrieve the newly generated id, we need an update that returns
 * some data (a JDBC 3 feature). Spring supports this with a keyholder.
 * <p>
 * Unfortunately, {@link JdbcTemplate#update(PreparedStatementCreator, KeyHolder)}
 * needs a {@link PreparedStatementCreator} which is a bit overwhelming
 * here.
 */
public void insertMessage(Author author, String text) {
    String sql = "INSERT INTO short_message(author_id, posted_time, message_text)" +
            " VALUES(?, ?, ?)";
    Timestamp currentTimestamp = Timestamp.valueOf(LocalDateTime.now());

    PreparedStatementCreatorFactory statementCreatorFactory =
            new PreparedStatementCreatorFactory(sql,
                    Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR);
    statementCreatorFactory.setReturnGeneratedKeys(true);
    statementCreatorFactory.setGeneratedKeysColumnNames("id");
    PreparedStatementCreator preparedStatementCreator =
            statementCreatorFactory.newPreparedStatementCreator(
                    new Object[]{author.getId(), currentTimestamp, text});

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int update = jdbcTemplate.update(preparedStatementCreator, keyHolder);
    log.info("auto-insert created {} row with key {}", update, keyHolder.getKey());
}
 
Example 17
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
private Integer saveOrderRecord(JdbcTemplate jdbcTemplate, final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 18
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
private Integer saveOrderRecord(JdbcTemplate jdbcTemplate, final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 19
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
private Integer saveOrderRecord(JdbcTemplate jdbcTemplate, final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 20
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
private Integer saveOrderRecord(JdbcTemplate jdbcTemplate, final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 21
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
private Integer saveOrderRecord(final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 22
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
private Integer saveOrderRecord(final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 23
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
private Integer saveOrderRecord(final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 24
Source Project: EasyTransaction   Source File: OrderService.java    License: Apache License 2.0 6 votes vote down vote up
public void cancelOrder(int orderId) {
	
	/**
	 * usually we will only update a status of order instead of delete
	 * but i did not define a status in the demo schema,so just delete instead
	 * 
	 * 通常不会直接删除之前创建记录,仅仅只是更新记录的状态
	 * 但是在测试的表结构里没有定义status字段,因此在样例代码里直接删除
	 */
	final String INSERT_SQL = "DELETE FROM `order` WHERE `order_id`= ?";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, orderId);
	            return ps;
	        }
	    },
	    keyHolder);
}
 
Example 25
Source Project: maven-framework-project   Source File: JdbcCustomerDAO.java    License: MIT License 6 votes vote down vote up
/**
 * 返回新增后自动生成的主键
 * @param customer
 * @return
 */
public int getAutoGeneratedID(final Customer customer){
	
	final String sql = "insert into CUSTOMER (name,age) values(?,?)";
	
	KeyHolder keyHolder = new GeneratedKeyHolder();
	
	jdbcTemplate.update(new PreparedStatementCreator() {
		
		@Override
		public PreparedStatement createPreparedStatement(Connection con)
				throws SQLException {
 				 //	autoGeneratedKeys
			 PreparedStatement pst = con.prepareStatement(sql, new String[] {"CUST_ID"});
			 pst.setString(1,customer.getName());//为第一个问号填充值
			 pst.setInt(2,customer.getAge());//为第二个问号填充值
			return pst;
		}
	},keyHolder);
	//返回插入后数据库生成的主键
	return keyHolder.getKey().intValue();
}
 
Example 26
Source Project: maven-framework-project   Source File: JdbcCalendarUserDao.java    License: MIT License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 27
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 28
Source Project: metacat   Source File: MySqlTagService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * findOrCreateTagItemByName.
 *
 * @param name name to find or create
 * @return Tag Item
 * @throws SQLException sql exception
 */
private TagItem findOrCreateTagItemByName(final String name) throws SQLException {
    TagItem result = get(name);
    if (result == null) {
        final KeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            final PreparedStatement ps = connection.prepareStatement(SQL_INSERT_TAG_ITEM,
                Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, name);
            ps.setString(2, config.getTagServiceUserAdmin());
            ps.setString(3, config.getTagServiceUserAdmin());
            return ps;
        }, holder);
        final Long id = holder.getKey().longValue();
        result = new TagItem();
        result.setName(name);
        result.setId(id);
    }
    return result;
}
 
Example 29
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 30
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}