use of org.springframework.jdbc.core.PreparedStatementCreator in project rdbcache by rdbcache.
the class Query method executeInsert.
public boolean executeInsert(boolean enableLocal, boolean enableRedis) {
params = new ArrayList<>();
boolean allOk = true;
for (int i = 0; i < pairs.size(); i++) {
KvPair pair = pairs.get(i);
KeyInfo keyInfo = anyKey.getAny(i);
String table = keyInfo.getTable();
Map<String, Object> map = pair.getData();
String autoIncKey = AppCtx.getDbaseOps().getTableAutoIncColumn(context, table);
boolean cacheUpdate = false;
if (!map.containsKey(autoIncKey) && keyInfo.getParams() != null && keyInfo.getParams().size() == 1) {
String stdClause = "(" + autoIncKey + " = ?)";
if (stdClause.equals(keyInfo.getClause())) {
map.put(autoIncKey, keyInfo.getParams().get(0));
cacheUpdate = true;
}
}
Map<String, Object> columns = keyInfo.getColumns();
AppCtx.getDbaseOps().convertDbMap(columns, map);
String fields = "", values = "";
params.clear();
for (Map.Entry<String, Object> entry : map.entrySet()) {
params.add(entry.getValue());
if (fields.length() != 0) {
fields += ", ";
values += ", ";
}
fields += entry.getKey();
values += "?";
}
sql = "insert into " + table + " (" + fields + ") values (" + values + ")";
LOGGER.trace("sql: " + sql);
LOGGER.trace("params: " + params.toString());
int rowCount = 0;
KeyHolder keyHolder = new GeneratedKeyHolder();
StopWatch stopWatch = context.startStopWatch("dbase", "jdbcTemplate.update");
try {
rowCount = jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps;
ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int i = 1;
for (Object param : params) {
ps.setObject(i++, param);
}
return ps;
}
}, keyHolder);
if (stopWatch != null)
stopWatch.stopNow();
} catch (Exception e) {
if (stopWatch != null)
stopWatch.stopNow();
allOk = false;
String msg = e.getCause().getMessage();
LOGGER.error(msg);
context.logTraceMessage(msg);
if (context.isSync()) {
throw new ServerErrorException(context, msg);
}
}
if (rowCount > 0) {
if (autoIncKey != null && keyHolder.getKey() != null) {
String keyValue = String.valueOf(keyHolder.getKey());
map.put(autoIncKey, keyValue);
cacheUpdate = true;
}
if (cacheUpdate) {
if (enableLocal) {
AppCtx.getLocalCache().putData(pair, keyInfo);
}
if (enableRedis) {
AppCtx.getRedisRepo().save(context, new KvPairs(pair), new AnyKey(keyInfo));
}
}
if (!Parser.prepareStandardClauseParams(context, pair, keyInfo)) {
String msg = "executeInsert failed when prepareStandardClauseParams for " + pair.getId();
LOGGER.error(msg);
context.logTraceMessage(msg);
if (context.isSync()) {
throw new ServerErrorException(context, msg);
}
}
LOGGER.trace("inserted " + pair.getId() + " into " + table);
} else {
allOk = false;
LOGGER.warn("failed to insert " + pair.getId() + " into " + table);
}
}
return allOk;
}
use of org.springframework.jdbc.core.PreparedStatementCreator in project leopard by tanhaichao.
the class JdbcMysqlImpl method insertForLastId.
@Override
public long insertForLastId(final String sql, final StatementParameter param) {
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
this.getJdbcTemplate().update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
param.setValues(pstmt);
return pstmt;
}
}, keyHolder);
return keyHolder.getKey().longValue();
}
use of org.springframework.jdbc.core.PreparedStatementCreator in project training_portal by training-portal.
the class GroupDaoJdbc method addGroup.
@Transactional
@Override
public Long addGroup(Group group) {
KeyHolder keyHolder = new GeneratedKeyHolder();
template.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement stmt = con.prepareStatement(ADD_GROUP, new String[] { "group_id" });
stmt.setString(1, group.getName());
stmt.setString(2, group.getDescription());
stmt.setDate(3, Date.valueOf(group.getCreationDate()));
stmt.setLong(4, group.getAuthorId());
return stmt;
}
}, keyHolder);
long groupId = keyHolder.getKey().longValue();
group.setGroupId(groupId);
logger.info("Group added: " + group);
return groupId;
}
use of org.springframework.jdbc.core.PreparedStatementCreator in project rdbcache by rdbcache.
the class MonitorRepoImpl method save.
@Override
public void save(Monitor monitor) {
Map<String, Object> map = Utils.toMap(monitor);
String fields = "";
String values = "";
final List<Object> params1 = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
params1.add(entry.getValue());
if (fields.length() != 0) {
fields += ", ";
values += ", ";
}
fields += entry.getKey();
values += "?";
}
final String sql1 = "insert into " + monitorTable + " (" + fields + ") values (" + values + ")";
int result = 0;
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
result = jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps;
ps = connection.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS);
int i = 1;
for (Object param : params1) {
ps.setObject(i++, param);
}
return ps;
}
}, keyHolder);
} catch (Exception e) {
e.getStackTrace();
return;
}
if (result == 0) {
return;
}
Long id = Long.valueOf(keyHolder.getKey().toString());
List<StopWatch> watches = monitor.getStopWatches();
if (watches != null && watches.size() > 0) {
map = AppCtx.getDbaseOps().getTableColumns(null, stopWatchTable);
Set<String> keySet = map.keySet();
fields = "";
values = "";
for (String key : keySet) {
if (fields.length() != 0) {
fields += ", ";
values += ", ";
}
fields += key;
values += "?";
}
final String sql2 = "insert into " + monitorTable + "(" + fields + ") values (" + values + ")";
List<Object[]> paramsList = new ArrayList<Object[]>();
for (StopWatch watch : watches) {
watch.setMonitorId(id);
map = Utils.toMap(watch);
List<Object> params = new ArrayList<>();
for (String key : keySet) {
if (map.containsKey(key)) {
params.add(map.get(key));
} else {
params.add(null);
}
}
paramsList.add(params.toArray());
}
jdbcTemplate.batchUpdate(sql2, paramsList);
}
}
use of org.springframework.jdbc.core.PreparedStatementCreator in project buffer-slayer by tramchamploo.
the class BatchJdbcTemplateTest method updateWithPreparedStatementCreator.
@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);
}
Aggregations