本文整理汇总了Java中org.springframework.jdbc.core.StatementCallback类的典型用法代码示例。如果您正苦于以下问题:Java StatementCallback类的具体用法?Java StatementCallback怎么用?Java StatementCallback使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
StatementCallback类属于org.springframework.jdbc.core包,在下文中一共展示了StatementCallback类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: saveMetrics
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
private void saveMetrics() throws IOException {
MetricRowBinaryHttpEntity httpEntity = new MetricRowBinaryHttpEntity(metrics);
clickHouseJdbcTemplate.execute(
(StatementCallback<Void>) stmt -> {
ClickHouseStatementImpl statement = (ClickHouseStatementImpl) stmt;
statement.sendStream(
httpEntity,
"INSERT INTO " + graphiteTable + " (metric, value, timestamp, date, updated)",
"RowBinary"
);
return null;
}
);
}
示例2: getCurrentTimeMillis
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
@Override
public Pair<Long, Long> getCurrentTimeMillis() {
return (Pair<Long, Long>) getJdbcTemplate().execute(new StatementCallback() {
@Override
public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
ResultSet rs = null;
try {
long time1 = System.currentTimeMillis();
rs = stmt.executeQuery("show @@status.time");
long time2 = System.currentTimeMillis();
if (rs.next()) {
return new Pair<Long, Long>(time1 + (time2 - time1) / 2, rs.getLong(1));
} else {
throw new IncorrectResultSizeDataAccessException(1, 0);
}
} finally {
if (rs != null) {
rs.close();
}
}
}
});
}
示例3: getNextId
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
/**
* 根据mysql的auto_increment生成主键
*
* @return 主键
*/
public static int getNextId() {
DataSource dataSource = ServiceLookup.getBean(DataSource.class);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate.execute(new StatementCallback<Integer>() {
@Override
public Integer doInStatement(Statement stmt) throws SQLException,
DataAccessException {
stmt.execute("replace into sequence(stub) values('a')");
ResultSet resultSet = stmt
.executeQuery("select last_insert_id() as id");
if (resultSet.next()) {
return resultSet.getInt("id");
}
throw new SQLException("generate id failed");
}
});
}
示例4: getCurrentTimeMillis
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
@Override
public Pair<Long, Long> getCurrentTimeMillis() {
return (Pair<Long, Long>) getJdbcTemplate().execute(new StatementCallback() {
@Override
public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
ResultSet rs = null;
try {
long time1 = System.currentTimeMillis();
rs = stmt.executeQuery("show @@status.time");
long time2 = System.currentTimeMillis();
if (rs.next()) {
return new Pair<Long, Long>(time1 + (time2 - time1) / 2, rs.getLong(1));
} else {
throw new IncorrectResultSizeDataAccessException(1, 0);
}
} finally {
if (rs != null) {
rs.close();
}
}
}
});
}
示例5: execute
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public Object execute(StatementCallback action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(getDataSource());
Statement stmt = null;
try {
Connection conToUse = con;
if (getNativeJdbcExtractor() != null &&
getNativeJdbcExtractor().isNativeConnectionNecessaryForNativeStatements()) {
conToUse = getNativeJdbcExtractor().getNativeConnection(con);
}
stmt = conToUse.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
applyStatementSettings(stmt);
Statement stmtToUse = stmt;
if (getNativeJdbcExtractor() != null) {
stmtToUse = getNativeJdbcExtractor().getNativeStatement(stmt);
}
Object result = action.doInStatement(stmtToUse);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
示例6: loadData
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource, final String schemaName) {
Assert.assertNotNull("DataSource could not be located.", dataSource);
if (schemaName == null || schemaName.equals("")) {
Assert.fail("Empty schema name given");
}
new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(final TransactionStatus status) {
verifyTestEnvironment(dataSource);
return new JdbcTemplate(dataSource).execute(new StatementCallback() {
public Object doInStatement(Statement statement) throws SQLException {
List<String> sqlStatements = new ArrayList<String>();
//
// djunk - add a per-class special test data loader,
// loads <testclassname>.sql from the same directory
// as the other SQL loaded.
if (callingTestClass != null) {
sqlStatements.addAll(getTestDataSQLStatements("src/test/config/sql/" + callingTestClass.getSimpleName() + "-cleanup.sql"));
}
for(String sql : sqlStatements){
if (!sql.startsWith("#") && !sql.startsWith("//") && !StringUtils.isEmpty(sql.trim())) {
// ignore comment lines in our sql reader.
statement.addBatch(sql);
}
}
statement.executeBatch();
return null;
}
});
}
});
}
示例7: loadData
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource, final String schemaName) {
LOG.info("Populating tables for schema " + schemaName);
Assert.assertNotNull("DataSource could not be located.", dataSource);
if (schemaName == null || schemaName.equals("")) {
Assert.fail("Empty schema name given");
}
new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
public Object doInTransaction(final TransactionStatus status) {
verifyTestEnvironment(dataSource);
return new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {
public Object doInStatement(Statement statement) throws SQLException {
if (callingTestClass != null) {
List<String> sqlStatements = getTestDataSQLStatements("src/test/config/sql/" + callingTestClass.getSimpleName() + ".sql");
for(String sql : sqlStatements){
if (!sql.startsWith("#") && !sql.startsWith("//") && !StringUtils.isEmpty(sql.trim())) {
// ignore comment lines in our sql reader.
statement.addBatch(sql);
}
}
}
statement.executeBatch();
return null;
}
});
}
});
}
示例8: loadData
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource, final String schemaName) {
LOG.info("Clearing tables for schema " + schemaName);
Assert.assertNotNull("DataSource could not be located.", dataSource);
if (schemaName == null || schemaName.equals("")) {
Assert.fail("Empty schema name given");
}
new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
public Object doInTransaction(final TransactionStatus status) {
verifyTestEnvironment(dataSource);
return new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {
public Object doInStatement(Statement statement) throws SQLException {
if (callingTestClass != null) {
List<String> sqlStatements = getTestDataSQLStatements("src/test/config/sql/" + callingTestClass.getSimpleName() + ".sql");
for(String sql : sqlStatements){
if (!sql.startsWith("#") && !sql.startsWith("//") && !StringUtils.isEmpty(sql.trim())) {
// ignore comment lines in our sql reader.
statement.addBatch(sql);
}
}
}
statement.executeBatch();
return null;
}
});
}
});
}
示例9: dumpSchema
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public static void dumpSchema(final DataSource datasource) {
new JdbcTemplate(datasource).execute(new StatementCallback<Object>() {
@Override
public Object doInStatement(Statement statement) throws SQLException, DataAccessException {
final ResultSet resultSet = statement.executeQuery("SHOW TABLES");
final List<String> tables = Lists.newArrayList();
while (resultSet.next()) {
tables.add(resultSet.getString(1));
}
resultSet.close();
for (final String table : tables) {
final ResultSet tableResultSet = statement.executeQuery("SELECT * FROM " + table);
while (tableResultSet.next()) {
ResultSetMetaData metadata = tableResultSet.getMetaData();
if (tableResultSet.isFirst()) {
System.out.println("\nTABLE: " + table.toUpperCase());
for (int column = 1; column <= metadata.getColumnCount(); column++) {
System.out.print(metadata.getColumnName(column) + " | ");
}
System.out.println();
}
for (int column = 1; column <= metadata.getColumnCount(); column++) {
System.out.print(tableResultSet.getString(column) + " | ");
}
System.out.println();
}
}
return null;
}
});
}
示例10: testActionListCount
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
@Test public void testActionListCount() throws Exception {
setUpOldSchool();
TransactionTemplate transactionTemplate = getTransactionTemplate();
transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
return TestUtilities.getJdbcTemplate().execute(new StatementCallback() {
public Object doInStatement(Statement stmt) {
try {
Connection conn = stmt.getConnection();
PreparedStatement ps = conn.prepareStatement("select distinct PRNCPL_ID from krew_actn_itm_t");
ResultSet rs = ps.executeQuery();
int emplIdCnt = 0;
int loopCnt = 0;
//do first 5 for time sake
while (rs.next() && ++loopCnt < 6) {
String workflowId = rs.getString(1);
PreparedStatement ps1 = conn.prepareStatement("select count(*) from krew_actn_itm_t where PRNCPL_ID = ?");
ps1.setString(1, workflowId);
ResultSet rsWorkflowIdCnt = ps1.executeQuery();
if (rsWorkflowIdCnt.next()) {
emplIdCnt = rsWorkflowIdCnt.getInt(1);
} else {
throw new Exception("WorkflowId " + workflowId + " didn't return a count. Test SQL invalid.");
}
Collection<ActionItem> actionList = getActionListService().findByPrincipalId(workflowId);
assertEquals("ActionItemService returned incorrect number of ActionItems for user " + workflowId + " ActionList", emplIdCnt, actionList.size());
ps1.close();
rsWorkflowIdCnt.close();
}
rs.close();
ps.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
});
}
});
}
示例11: execute
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public boolean execute(final String sql) throws DataAccessException {
if (log.isDebugEnabled()) {
log.debug("Executing SQL statement [" + sql + "]");
}
class ExecuteStatementCallback implements StatementCallback<Boolean>, SqlProvider {
public Boolean doInStatement(Statement stmt) throws SQLException {
return stmt.execute(sql);
}
public String getSql() {
return sql;
}
}
return template.execute(new ExecuteStatementCallback());
}
示例12: execute
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
return delegate.execute(action);
}
示例13: clearTables
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
public static void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource, final String edenSchemaName, final List<String> dontClear) {
LOG.info("Clearing tables for schema " + edenSchemaName);
if (dataSource == null) {
Assert.fail("Null data source given");
}
if (edenSchemaName == null || edenSchemaName.equals("")) {
Assert.fail("Empty eden schema name given");
}
new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
verifyTestEnvironment(dataSource);
JdbcTemplate template = new JdbcTemplate(dataSource);
return template.execute(new StatementCallback() {
public Object doInStatement(Statement statement) throws SQLException {
List<String> reEnableConstraints = new ArrayList<String>();
ResultSet resultSet = statement.getConnection().getMetaData().getTables(null, edenSchemaName, null, new String[] { "TABLE" });
while (resultSet.next()) {
String tableName = resultSet.getString("TABLE_NAME");
if (tableName.startsWith("EN_") && !dontClear.contains(tableName)) {
ResultSet keyResultSet = statement.getConnection().getMetaData().getExportedKeys(null, edenSchemaName, tableName);
while (keyResultSet.next()) {
String fkName = keyResultSet.getString("FK_NAME");
String fkTableName = keyResultSet.getString("FKTABLE_NAME");
statement.addBatch("ALTER TABLE "+fkTableName+" DISABLE CONSTRAINT "+fkName);
reEnableConstraints.add("ALTER TABLE "+fkTableName+" ENABLE CONSTRAINT "+fkName);
}
keyResultSet.close();
statement.addBatch("DELETE FROM "+tableName);
}
}
for (String constraint : reEnableConstraints) {
statement.addBatch(constraint);
}
statement.executeBatch();
resultSet.close();
return null;
}
});
}
});
LOG.info("Tables successfully cleared for schema " + edenSchemaName);
}
示例14: testActionListCount
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
@Test public void testActionListCount() throws Exception {
setUpOldSchool();
TransactionTemplate transactionTemplate = getTransactionTemplate();
transactionTemplate.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return TestUtilities.getJdbcTemplate().execute(new StatementCallback() {
@Override
public Object doInStatement(Statement stmt) {
try {
Connection conn = stmt.getConnection();
PreparedStatement ps = conn.prepareStatement("select distinct PRNCPL_ID from krew_actn_itm_t");
ResultSet rs = ps.executeQuery();
int emplIdCnt = 0;
int loopCnt = 0;
//do first 5 for time sake
while (rs.next() && ++loopCnt < 6) {
String workflowId = rs.getString(1);
PreparedStatement ps1 = conn.prepareStatement("select count(*) from krew_actn_itm_t where PRNCPL_ID = ?");
ps1.setString(1, workflowId);
ResultSet rsWorkflowIdCnt = ps1.executeQuery();
if (rsWorkflowIdCnt.next()) {
emplIdCnt = rsWorkflowIdCnt.getInt(1);
} else {
throw new Exception("WorkflowId " + workflowId + " didn't return a count. Test SQL invalid.");
}
Collection<ActionItem> actionList = getActionListService().findByPrincipalId(workflowId);
assertEquals("ActionItemService returned incorrect number of ActionItems for user " + workflowId + " ActionList", emplIdCnt, actionList.size());
ps1.close();
rsWorkflowIdCnt.close();
}
rs.close();
ps.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
});
}
});
}
示例15: testActionListMaxActionItemDateAssignedAndCountForUser
import org.springframework.jdbc.core.StatementCallback; //导入依赖的package包/类
@Test
public void testActionListMaxActionItemDateAssignedAndCountForUser() throws Exception {
// sanity check first - just attempt to call the method
getActionListService().getMaxActionItemDateAssignedAndCountForUser("123456");
setUpOldSchool();
TransactionTemplate transactionTemplate = getTransactionTemplate();
transactionTemplate.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return TestUtilities.getJdbcTemplate().execute(new StatementCallback() {
@Override
public Object doInStatement(Statement stmt) {
try {
Connection conn = stmt.getConnection();
PreparedStatement ps = conn.prepareStatement(
"select distinct PRNCPL_ID from krew_actn_itm_t");
ResultSet rs = ps.executeQuery();
long cnt = 0;
Date maxDate = null;
int loopCnt = 0;
//do first 5 for time sake
while (rs.next() && ++loopCnt < 6) {
String workflowId = rs.getString(1);
PreparedStatement ps1 = conn.prepareStatement(
"select max(ASND_DT) as max_date, count(distinct(doc_hdr_id)) as total_records"
+ " from ("
+ " select ASND_DT,doc_hdr_id "
+ " from KREW_ACTN_ITM_T where prncpl_id=? "
+ " group by ASND_DT,doc_hdr_id "
+ " ) T");
ps1.setString(1, workflowId);
ResultSet rsWorkflowIdCnt = ps1.executeQuery();
if (rsWorkflowIdCnt.next()) {
maxDate = rsWorkflowIdCnt.getTimestamp(1);
cnt = rsWorkflowIdCnt.getLong(2);
} else {
throw new Exception(
"WorkflowId " + workflowId + " didn't return a result set. Test SQL invalid.");
}
List<Object> ls = getActionListService().getMaxActionItemDateAssignedAndCountForUser(workflowId);
assertEquals((Long) cnt, ls.get(1));
assertEquals(maxDate, ls.get(0));
ps1.close();
rsWorkflowIdCnt.close();
}
if ( loopCnt == 0 ) {
Assert.fail( "ERROR - NO PRINCIPAL IDs RETURNED FROM ACTION ITEM SEARCH - TEST DID NOT RUN" );
}
rs.close();
ps.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
});
}
});
}