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(); }
private <S extends T> S insertWithAutoGeneratedKey(S entity, Map<String, Object> columns) { removeIdColumns(columns); final String insertQuery = sqlGenerator.insert(table, columns); final Object[] queryParams = columns.values().toArray(); final GeneratedKeyHolder key = new GeneratedKeyHolder(); jdbcOps.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { String idColumnName = table.getPkColumns().get(0); PreparedStatement ps = con.prepareStatement(insertQuery, new String[]{idColumnName}); for (int i = 0; i < queryParams.length; ++i) { ps.setObject(i + 1, queryParams[i]); } return ps; } }, key); return postInsert(entity, key.getKey()); }
/** * * @param sql * @param args * @return */ public int update(final String sql, final List<?> args) { if(logger.isDebugEnabled()){ StringBuilder builder = new StringBuilder(); builder.append("{sql: \"").append(sql).append("\"; parameters:").append(args); logger.debug(builder.toString()); } return jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql); populate(ps, args); return ps; } }); }
@Transactional public User create(String tenantSchema, final User user) { final String sql = MessageFormat.format(TENANT_SQL_TEMPLATE, tenantSchema, "insert into user(name,password) values(?,?)"); KeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, user.getName()); ps.setString(2, user.getPassword()); return ps; } }, holder); int newUserId = holder.getKey().intValue(); user.setId(newUserId); return user; }
public long getCurrentGithubId() { KeyHolder keyHolder = new GeneratedKeyHolder(); String sql = "SELECT stat_id FROM github_stats WHERE stat_date = current_date()"; long statId = -1; try { statId = jdbcTemplate.queryForObject(sql, Long.class); } catch (EmptyResultDataAccessException e) { jdbcTemplate.update( new PreparedStatementCreator() { String INSERT_SQL = "INSERT INTO github_stats (stat_date) VALUES (current_date())"; public PreparedStatement createPreparedStatement(Connection cn) throws SQLException { PreparedStatement ps = cn.prepareStatement(INSERT_SQL, new String[] {"stat_id"}); return ps; } }, keyHolder); statId = keyHolder.getKey().longValue(); } logger.info("Current GitHub Stats ID: " + statId); return statId; }
@Test public void githubStatRecordKeyReturned() throws Exception { KeyHolder keyHolder = new GeneratedKeyHolder(); long statId = -1L; try { statId = jdbcTemplate.queryForObject("SELECT stat_id FROM github_stats WHERE stat_date = '2010-10-10'", Long.class); } catch (EmptyResultDataAccessException e) { jdbcTemplate.update( new PreparedStatementCreator() { String INSERT_SQL = "INSERT INTO github_stats (stat_date) VALUES ('2010-10-10')"; public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[]{"stat_id"}); return ps; } }, keyHolder); statId = keyHolder.getKey().longValue(); } assertThat(statId).isGreaterThan(0); }
public Idea insert(Idea idea, User currentUser) { String sql = "insert into idea (title, description, user_id) values (?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" }); ps.setString(1, idea.getTitle()); ps.setString(2, idea.getDescription()); ps.setLong(3, currentUser.getId()); return ps; } }, keyHolder); idea.setId(keyHolder.getKey().longValue()); return idea; }
@Test public void updateWithPreparedStatementCreator() { reporter = AsyncReporter.builder(new JdbcTemplateSender(underlying)) .pendingMaxMessages(2) .bufferedMaxMessages(2) .messageTimeout(0, TimeUnit.MILLISECONDS) .build(); batchJdbcTemplate = new BatchJdbcTemplate(underlying, reporter); PreparedStatementCreatorFactory creatorFactory = new PreparedStatementCreatorFactory(INSERTION); creatorFactory.addParameter(new SqlParameter(Types.VARCHAR)); creatorFactory.addParameter(new SqlParameter(Types.TIMESTAMP)); PreparedStatementCreator creator = creatorFactory .newPreparedStatementCreator(new Object[]{randomString(), new Date()}); batchJdbcTemplate.update(creator); batchJdbcTemplate.update(creator); reporter.flush(); int rowCount = batchJdbcTemplate.queryForObject("SELECT COUNT(1) FROM test;", Integer.class); assertEquals(2, rowCount); }
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; }
public Long insertAndGetKey(final String sql, final Object... args) { final String mSql = initSql(sql); KeyHolder keyHolder = new GeneratedKeyHolder(); getJdbcTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(mSql, Statement.RETURN_GENERATED_KEYS); if (args != null && args.length > 0) { for (int index = 0; index < args.length; index++) { ps.setObject((index + 1), args[index]); } } return ps; } }, keyHolder); Long generatedId = keyHolder.getKey().longValue(); return generatedId; }
private Long createDefaultAuthzZone(final JdbcTemplate jdbcTemplate) { final String insertZoneSql = "INSERT INTO authorization_zone (name, description, subdomain) " + "VALUES (?,?,?)"; KeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(insertZoneSql, new String[] { "id" }); ps.setString(1, "apm-migrated"); ps.setString(2, "APM Migrated Zone from mvp1"); ps.setString(3, "apm-migrated"); return ps; } }, holder); return holder.getKey().longValue(); }
@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(); }
public boolean saveVisitorAndComment(final Comment comment){ jdbcTemplate = new JdbcTemplate(dataSource); final String sql = "INSERT INTO visitors(VisitorName,Email) VALUES(?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); int result = jdbcTemplate.update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement pst = con.prepareStatement(sql, new String[] {"Id"}); pst.setString(1, comment.getName()); pst.setString(2, comment.getEmail()); return pst; } }, keyHolder); final Long lastId = (Long)keyHolder.getKey(); if(result != 0){ comment.setCommentatorId(lastId.intValue()); return saveVisitor(comment); } else { return false; } }
public Permission createPermission(final Permission permission) { final String sql = "insert into sys_permissions(permission, description, available) values(?,?,?)"; GeneratedKeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" }); psst.setString(1, permission.getPermission()); psst.setString(2, permission.getDescription()); psst.setBoolean(3, permission.getAvailable()); return psst; } }, keyHolder); permission.setId(keyHolder.getKey().longValue()); return permission; }
public Role createRole(final Role role) { final String sql = "insert into sys_roles(role, description, available) values(?,?,?)"; GeneratedKeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" }); psst.setString(1, role.getRole()); psst.setString(2, role.getDescription()); psst.setBoolean(3, role.getAvailable()); return psst; } }, keyHolder); role.setId(keyHolder.getKey().longValue()); return role; }
public User createUser(final User user) { final String sql = "insert into sys_users(username, password, salt, locked) values(?,?,?, ?)"; GeneratedKeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" }); psst.setString(1, user.getUsername()); psst.setString(2, user.getPassword()); psst.setString(3, user.getSalt()); psst.setBoolean(4, user.getLocked()); return psst; } }, keyHolder); user.setId(keyHolder.getKey().longValue()); return user; }