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

The following examples show how to use org.springframework.jdbc.support.KeyHolder. 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: 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 2
@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 3
@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 4
@Override
public int update(
		String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
		throws DataAccessException {

	ParsedSql parsedSql = getParsedSql(sql);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null);
	List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
	PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters);
	if (keyColumnNames != null) {
		pscf.setGeneratedKeysColumnNames(keyColumnNames);
	}
	else {
		pscf.setReturnGeneratedKeys(true);
	}
	return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder);
}
 
Example 5
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 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
Source Project: nh-micro   Source File: MicroMetaDao.java    License: Apache License 2.0 6 votes vote down vote up
public int insertObj(final String sql,final Object[] paramArray, KeyHolder keyHolder, final String idCol) {

		JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
		logger.debug(sql);
		logger.debug(Arrays.toString(paramArray));
		Integer retStatus=jdbcTemplate.update(new PreparedStatementCreator() { 

			public PreparedStatement createPreparedStatement(Connection con) 
			throws SQLException { 
					String[] keyColNames=new String[1];
					keyColNames[0]=idCol;
					PreparedStatement ps=con.prepareStatement(sql,keyColNames); 
					if(paramArray!=null){
						int size=paramArray.length;
						for(int i=0;i<size;i++){
							ps.setObject(i+1, paramArray[i]);
						}
					}
		
					return ps; 
				} 
			}, keyHolder);	
		return retStatus;
	}
 
Example 8
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 9
Source Project: java-technology-stack   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 10
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 11
Source Project: dapeng-soa   Source File: TransactionDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 插入记录,返回id
 *
 * @param g
 * @return
 */
@Override
public Integer insert(TGlobalTransaction g) {

    final String strSql = "insert into global_transactions(status, curr_sequence, created_at, created_by, updated_by) values(?, ?, ?, ?, ?)";
    KeyHolder keyHolder = new GeneratedKeyHolder();

    this.getJdbcTemplate().update(conn -> {
        int i = 0;
        PreparedStatement ps = conn.prepareStatement(strSql);
        ps = conn.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS);
        ps.setInt(++i, g.getStatus().getValue());
        ps.setInt(++i, g.getCurrSequence());
        ps.setTimestamp(++i, new Timestamp(g.getCreatedAt() == null ? new java.util.Date().getTime() : g.getCreatedAt().getTime()));
        ps.setInt(++i, g.getCreatedBy());
        ps.setInt(++i, g.getCreatedBy());
        return ps;
    }, keyHolder);

    return keyHolder.getKey().intValue();
}
 
Example 12
@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 13
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 14
@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 15
Source Project: poli   Source File: ComponentDao.java    License: MIT License 6 votes vote down vote up
public long insert(Component c) {
    String sql = "INSERT INTO p_component(report_id, datasource_id, title, sql_query, width, height, x, y, data, drill_through, style, type, sub_type) "
                + "VALUES(:report_id, :datasource_id, :title, :sql_query, :width, :height, :x, :y, :data, :drill_through, :style, :type, :sub_type)";
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue(Component.REPORT_ID, c.getReportId());
    params.addValue(Component.DATASOURCE_ID, c.getJdbcDataSourceId());
    params.addValue(Component.TITLE, c.getTitle());
    params.addValue(Component.SQL_QUERY, c.getSqlQuery());
    params.addValue(Component.WIDTH, c.getWidth());
    params.addValue(Component.HEIGHT, c.getHeight());
    params.addValue(Component.X, c.getX());
    params.addValue(Component.Y, c.getY());
    params.addValue(Component.DATA, c.getData());
    params.addValue(Component.DRILL_THROUGH, c.getDrillThrough());
    params.addValue(Component.STYLE, c.getStyle());
    params.addValue(Component.TYPE, c.getType());
    params.addValue(Component.SUB_TYPE, c.getSubType());

    KeyHolder keyHolder = new GeneratedKeyHolder();
    npjt.update(sql, params, keyHolder, new String[] { Report.ID});
    return keyHolder.getKey().longValue();
}
 
Example 16
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 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(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(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(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 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: 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 24
Source Project: ZenQuery   Source File: JdbcQueryVersionDAO.java    License: Apache License 2.0 6 votes vote down vote up
public Number insert(final QueryVersion queryVersion) {
    final String sql = "INSERT INTO query_versions (content, version, is_current_version, query_id) VALUES (?, ?, ?, ?)";

    jdbcTemplate = new JdbcTemplate(dataSource);
    KeyHolder keyHolder = new GeneratedKeyHolder();

    PreparedStatementCreator preparedStatementCreator = new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection)
                throws SQLException {
            PreparedStatement preparedStatement = connection.prepareStatement(sql, new String[] { "id" });

            preparedStatement.setString(1, queryVersion.getContent());
            preparedStatement.setInt(2, queryVersion.getVersion());
            preparedStatement.setBoolean(3, queryVersion.getIsCurrentVersion());
            preparedStatement.setInt(4, queryVersion.getQueryId());

            return preparedStatement;
        }
    };
    jdbcTemplate.update(
            preparedStatementCreator,
            keyHolder
    );

    return keyHolder.getKey();
}
 
Example 25
Source Project: spring-analysis-note   Source File: SqlUpdate.java    License: MIT License 5 votes vote down vote up
/**
 * Method to execute the update given arguments and
 * retrieve the generated keys using a KeyHolder.
 * @param params array of parameter objects
 * @param generatedKeyHolder the KeyHolder that will hold the generated keys
 * @return the number of rows affected by the update
 */
public int update(Object[] params, KeyHolder generatedKeyHolder) throws DataAccessException {
	if (!isReturnGeneratedKeys() && getGeneratedKeysColumnNames() == null) {
		throw new InvalidDataAccessApiUsageException(
				"The update method taking a KeyHolder should only be used when generated keys have " +
				"been configured by calling either 'setReturnGeneratedKeys' or " +
				"'setGeneratedKeysColumnNames'.");
	}
	validateParameters(params);
	int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(params), generatedKeyHolder);
	checkRowsAffected(rowsAffected);
	return rowsAffected;
}
 
Example 26
Source Project: Spring-Security-Third-Edition   Source File: JdbcEventDao.java    License: MIT License 5 votes vote down vote up
@Override
public int createEvent(final Event event) {
    if (event == null) {
        throw new IllegalArgumentException("event cannot be null");
    }
    if (event.getId() != null) {
        throw new IllegalArgumentException("event.getId() must be null when creating a new Message");
    }
    final CalendarUser owner = event.getOwner();
    if (owner == null) {
        throw new IllegalArgumentException("event.getOwner() cannot be null");
    }
    final CalendarUser attendee = event.getAttendee();
    if (attendee == null) {
        throw new IllegalArgumentException("attendee.getOwner() cannot be null");
    }
    final Calendar when = event.getWhen();
    if(when == null) {
        throw new IllegalArgumentException("event.getWhen() cannot be null");
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into events (when,summary,description,owner,attendee) values (?, ?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setDate(1, new java.sql.Date(when.getTimeInMillis()));
            ps.setString(2, event.getSummary());
            ps.setString(3, event.getDescription());
            ps.setInt(4, owner.getId());
            ps.setObject(5, attendee == null ? null : attendee.getId());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 27
Source Project: Spring-Security-Third-Edition   Source File: JdbcEventDao.java    License: MIT License 5 votes vote down vote up
@Override
public int createEvent(final Event event) {
    if (event == null) {
        throw new IllegalArgumentException("event cannot be null");
    }
    if (event.getId() != null) {
        throw new IllegalArgumentException("event.getId() must be null when creating a new Message");
    }
    final CalendarUser owner = event.getOwner();
    if (owner == null) {
        throw new IllegalArgumentException("event.getOwner() cannot be null");
    }
    final CalendarUser attendee = event.getAttendee();
    if (attendee == null) {
        throw new IllegalArgumentException("attendee.getOwner() cannot be null");
    }
    final Calendar when = event.getWhen();
    if(when == null) {
        throw new IllegalArgumentException("event.getWhen() cannot be null");
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into events (when,summary,description,owner,attendee) values (?, ?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setDate(1, new java.sql.Date(when.getTimeInMillis()));
            ps.setString(2, event.getSummary());
            ps.setString(3, event.getDescription());
            ps.setInt(4, owner.getId());
            ps.setObject(5, attendee == null ? null : attendee.getId());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 28
Source Project: spring-analysis-note   Source File: NamedParameterJdbcTemplate.java    License: MIT License 5 votes vote down vote up
@Override
public int update(
		String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, @Nullable String[] keyColumnNames)
		throws DataAccessException {

	PreparedStatementCreator psc = getPreparedStatementCreator(sql, paramSource, pscf -> {
		if (keyColumnNames != null) {
			pscf.setGeneratedKeysColumnNames(keyColumnNames);
		}
		else {
			pscf.setReturnGeneratedKeys(true);
		}
	});
	return getJdbcOperations().update(psc, generatedKeyHolder);
}
 
Example 29
Source Project: maven-framework-project   Source File: JdbcEventDao.java    License: MIT License 5 votes vote down vote up
@Override
public int createEvent(final Event event) {
    if (event == null) {
        throw new IllegalArgumentException("event cannot be null");
    }
    if (event.getId() != null) {
        throw new IllegalArgumentException("event.getId() must be null when creating a new Message");
    }
    final CalendarUser owner = event.getOwner();
    if (owner == null) {
        throw new IllegalArgumentException("event.getOwner() cannot be null");
    }
    final CalendarUser attendee = event.getAttendee();
    if (attendee == null) {
        throw new IllegalArgumentException("attendee.getOwner() cannot be null");
    }
    final Calendar when = event.getWhen();
    if(when == null) {
        throw new IllegalArgumentException("event.getWhen() cannot be null");
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into events (when,summary,description,owner,attendee) values (?, ?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setDate(1, new java.sql.Date(when.getTimeInMillis()));
            ps.setString(2, event.getSummary());
            ps.setString(3, event.getDescription());
            ps.setInt(4, owner.getId());
            ps.setObject(5, attendee == null ? null : attendee.getId());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 30
Source Project: nh-micro   Source File: MicroMetaDao.java    License: Apache License 2.0 5 votes vote down vote up
public int insertObj(String tableName, String cols,String values,final Object[] paramArray, KeyHolder keyHolder, final String idCol) {
	//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
	//String tableName=changeTableNameCase(otableName);
	JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
	String timeName=getTimeName();
	if(autoOperTime){
		cols="create_time,update_time,"+cols;
		values=timeName+","+timeName+","+values;
	}
	final String sql = "insert into " + tableName + " ("+cols+") values ("+values+")";
	logger.debug(sql);
	logger.debug(Arrays.toString(paramArray));

	//Integer retStatus=jdbcTemplate.update(sql,paramArray);
	Integer retStatus=jdbcTemplate.update(new PreparedStatementCreator() { 

		public PreparedStatement createPreparedStatement(Connection con) 
		throws SQLException { 
				String[] keyColNames=new String[1];
				keyColNames[0]=idCol;
				PreparedStatement ps=con.prepareStatement(sql,keyColNames); 
				if(paramArray!=null){
					int size=paramArray.length;
					for(int i=0;i<size;i++){
						ps.setObject(i+1, paramArray[i]);
					}
				}
	
				return ps; 
			} 
		}, keyHolder);		
	
	return retStatus;
}