org.springframework.jdbc.support.KeyHolder Java Examples

The following examples show how to use org.springframework.jdbc.support.KeyHolder. 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 File: JdbcTacoRepository.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: OrderService.java    From EasyTransaction with 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 #3
Source File: OrderService.java    From EasyTransaction with 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 #4
Source File: JdbcQueryVersionDAO.java    From ZenQuery with 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 #5
Source File: OrderService.java    From EasyTransaction with 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 #6
Source File: JdbcCalendarUserDao.java    From Spring-Security-Third-Edition with 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 #7
Source File: OrderService.java    From EasyTransaction with 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 #8
Source File: JdbcCalendarUserDao.java    From Spring-Security-Third-Edition with 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 #9
Source File: MySqlTagService.java    From metacat with 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 #10
Source File: NamedParameterJdbcTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #11
Source File: SqlUpdateTests.java    From spring-analysis-note with 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 #12
Source File: OrderService.java    From EasyTransaction with 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 #13
Source File: OrderService.java    From EasyTransaction with 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 #14
Source File: JdbcCalendarUserDao.java    From maven-framework-project with 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 #15
Source File: SqlUpdateTests.java    From java-technology-stack with 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 #16
Source File: TransactionDaoImpl.java    From dapeng-soa with 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 #17
Source File: JdbcCalendarUserDao.java    From Spring-Security-Third-Edition with 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 #18
Source File: P2_InsertOp.java    From nimble-orm with 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 #19
Source File: TradeOrderRepository.java    From tcc-transaction with 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 #20
Source File: MicroMetaDao.java    From nh-micro with 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 #21
Source File: JdbcCalendarUserDao.java    From Spring-Security-Third-Edition with 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 #22
Source File: ComponentDao.java    From poli with 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 #23
Source File: JdbcCalendarUserDao.java    From Spring-Security-Third-Edition with 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 #24
Source File: OrderService.java    From EasyTransaction with 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 #25
Source File: JdbcTestHelper.java    From nestedj with MIT License 5 votes vote down vote up
public void save(TestNode node) {
    KeyHolder keyHolder = new JdbcKeyHolder();
    jdbcTemplate.update(con -> {
        String insertQuery = String.format("insert into nested_nodes(id, tree_left, tree_level, tree_right, node_name, parent_id, discriminator) values(next value for SEQ,%s,%s,%s,'%s',%s,'%s')",
                node.getTreeLeft(), node.getTreeLevel(), node.getTreeRight(), node.getName(), node.getParentId(), node.getDiscriminator()
        );
        return con.prepareStatement(insertQuery, new String[]{"id"});
    }, keyHolder);
    node.setId((Long) keyHolder.getKey());
}
 
Example #26
Source File: JdbcEventDao.java    From Spring-Security-Third-Edition with 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 File: GenericDao.java    From disconf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private int createAndFetchUpdateRow(ENTITY entity, final String sql, final List<Object> params) {

    KeyHolder keyHolder = new GeneratedKeyHolder();
    recordLog(sql);

    // 执行操作
    int rowCount = this.jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(sql);
            int index = 1;
            for (Object param : params) {
                ps.setObject(index++, param);
            }
            return ps;
        }
    }, keyHolder);

    // 如果插入成功则获取keyHolder中的key
    if (rowCount != 0) {
        Class<KEY> keyClass = orMapping.getKeyClass();
        if (keyClass.equals(Integer.class)) {
            entity.setId((KEY) Integer.valueOf(keyHolder.getKey().intValue()));
        } else if (keyClass.equals(Long.class)) {
            entity.setId((KEY) Long.valueOf(keyHolder.getKey().longValue()));
        }
    }

    return rowCount;
}
 
Example #28
Source File: DbDicDao.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public int insertName(String name) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    PreparedStatementCreator psc = connection -> {
        PreparedStatement ps = connection.prepareStatement(insertNameSql, Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, name);
        return ps;
    };
    jdbcTemplate.update(psc, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example #29
Source File: JdbcEventDao.java    From Spring-Security-Third-Edition with 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 File: MessageRepositoryJDBCTemplate.java    From tutorials with MIT License 5 votes vote down vote up
public long insert(final String message) {
    
    KeyHolder keyHolder = new GeneratedKeyHolder();

    jdbcTemplate.update(connection -> {
        PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL);
        ps.setString(1, message);
        return ps;
    }, keyHolder);

    return (long) keyHolder.getKey();
}