public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler){ this.jdbcTemplate = jdbcTemplate; this.lobHandler = lobHandler; // 初始化transction this.transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource())); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 初始化一些数据 jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection c) throws SQLException, DataAccessException { DatabaseMetaData meta = c.getMetaData(); databaseName = meta.getDatabaseProductName(); databaseMajorVersion = meta.getDatabaseMajorVersion(); databaseMinorVersion = meta.getDatabaseMinorVersion(); return null; } }); initTables(jdbcTemplate); }
/** * 查找sqlserver的主键索引 * * @param dbInofId * @param tableName * @return 返回主键索引的值 * @throws Exception */ public String findSqlServerPKIndex(String dbInofId, final String tableName) throws Exception { DataSource ds = getDataSourceByDbInfoId(dbInofId); JdbcTemplate jdbcTemplate = SpringJdbcUtils.getJdbcTemplate(ds); String s = jdbcTemplate.execute(new ConnectionCallback<String>() { public String doInConnection(Connection con) throws SQLException, DataAccessException { String pkName = null; if (con.getMetaData().getURL().toLowerCase().contains("sqlserver")) { CallableStatement call = con.prepareCall("{call sp_pkeys(?)}"); call.setString(1, tableName); ResultSet rs = call.executeQuery(); while (rs.next()) { pkName = rs.getString("PK_NAME"); } } return pkName; } }); return s; }
/** * 根据DataSource判断一下数据库类型 * * @param dataSource * @return */ public static DbType judgeDbType(DataSource dataSource) { final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return (DbType) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection c) throws SQLException, DataAccessException { DatabaseMetaData meta = c.getMetaData(); String databaseName = meta.getDatabaseProductName(); String version = meta.getDatabaseProductVersion(); if (StringUtils.startsWithIgnoreCase(databaseName, "oracle")) { return DbType.ORACLE; } else if (StringUtils.startsWithIgnoreCase(databaseName, "mysql")) { if (StringUtils.contains(version, "-TDDL-")) { return DbType.DRDS; } else { return DbType.MYSQL; } } else { throw new YuGongException("unknow database type " + databaseName); } } }); }
@Test public void multipleDataSources() { load(MultipleDataSourcesConfig.class); PublicMetrics bean = this.context.getBean(DataSourcePublicMetrics.class); Collection<Metric<?>> metrics = bean.metrics(); assertMetrics(metrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); // Hikari won't work unless a first connection has been retrieved JdbcTemplate jdbcTemplate = new JdbcTemplate( this.context.getBean("hikariDS", DataSource.class)); jdbcTemplate.execute(new ConnectionCallback<Void>() { @Override public Void doInConnection(Connection connection) throws SQLException, DataAccessException { return null; } }); Collection<Metric<?>> anotherMetrics = bean.metrics(); assertMetrics(anotherMetrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.hikariDS.active", "datasource.hikariDS.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); }
@Test public void getPoolSizeOneConnection() { JdbcTemplate jdbcTemplate = new JdbcTemplate( getDataSourceMetadata().getDataSource()); jdbcTemplate.execute(new ConnectionCallback<Void>() { @Override public Void doInConnection(Connection connection) throws SQLException, DataAccessException { assertThat(getDataSourceMetadata().getActive()) .isEqualTo(Integer.valueOf(1)); assertThat(getDataSourceMetadata().getUsage()) .isEqualTo(Float.valueOf(0.5F)); return null; } }); }
/** * Gets the platform information from the {@link DataSource}. * * @param dataSource the {@link DataSource} to consult. * @return the platform information from the {@link DataSource}. */ public static DatabasePlatformInfo detectPlatform(DataSource dataSource) { if (dataSource == null) { throw new IllegalArgumentException("DataSource must not be null."); } DatabasePlatformInfo platformInfo = platformCache.get(dataSource); if (platformInfo == null) { JdbcTemplate template = new JdbcTemplate(dataSource); platformCache.put(dataSource, template.execute(new ConnectionCallback<DatabasePlatformInfo>() { @Override public DatabasePlatformInfo doInConnection( Connection connection) throws SQLException, DataAccessException { DatabaseMetaData metadata = connection.getMetaData(); String vendorName = metadata.getDatabaseProductName(); int version = metadata.getDatabaseMajorVersion(); return new DatabasePlatformInfo(vendorName, version); } })); if (platformInfo == null) { platformInfo = platformCache.get(dataSource); } } return platformInfo; }
public static void verifyTestEnvironment(DataSource dataSource) { if (dataSource == null) { Assert.fail("Could not locate the data source."); } JdbcTemplate template = new JdbcTemplate(dataSource); template.execute(new ConnectionCallback() { public Object doInConnection(Connection connection) throws SQLException { ResultSet resultSet = connection.getMetaData().getTables(null, null, TEST_TABLE_NAME, null); if (!resultSet.next()) { LOG.error("No table named '"+TEST_TABLE_NAME+"' was found in the configured database. " + "You are attempting to run tests against a non-test database!!!"); LOG.error("The test environment will not start up properly!!!"); Assert.fail("No table named '"+TEST_TABLE_NAME+"' was found in the configured database. " + "You are attempting to run tests against a non-test database!!!"); } return null; } }); }
protected int countTableResults(String valueToVerify) { final String valueToCheck = valueToVerify; final DataSource dataSource = TestHarnessServiceLocator.getDataSource(); return (Integer) new JdbcTemplate(dataSource).execute(new ConnectionCallback() { public Object doInConnection(final Connection connection) throws SQLException { Statement statement = null; try { statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); final ResultSet resultSet = statement.executeQuery("Select * from " + TEST_TABLE_NAME + " where COL = '" + valueToCheck + "'"); assertNotNull("ResultSet should not be null",resultSet); int count = 0; while (resultSet.next()) { count++; } return count; } finally { if (statement != null) { statement.close(); } } } }); }
/** * @return a list of the table names, retrieved via the connection metadata object. The excludeTableNames * property can be used to ignore certain table names. */ protected List<String> getTableNames() { return new JdbcTemplate(dataSource).execute(new ConnectionCallback<List<String>>() { @Override public List<String> doInConnection(Connection con) throws SQLException, DataAccessException { ResultSet rs = con.getMetaData().getTables(null, null, "%", new String[]{"TABLE"}); List<String> list = new ArrayList<>(); while (rs.next()) { String name = rs.getString("TABLE_NAME"); if (excludeTableNames == null || !excludeTableNames.contains(name)) { list.add(name); } } return list; } }); }
@Override @SuppressWarnings("unchecked") public <R, X> R execute(final TemplateCallback<R,X> callback) { Class<?> type = callback.getTemplateType(); if(ClassUtils.isAssignable(Connection.class, type)){ return template.execute(new ConnectionCallback<R>() { public R doInConnection(Connection conn) throws SQLException, DataAccessException { return callback.doInTemplate((X)conn); } }); }else if(ClassUtils.isAssignable(JdbcTemplate.class, type)){ return callback.doInTemplate((X)template); }else{ throw new RuntimeException("Template Type is wrong."); } }
@Override public Page<T> findAll(final Predicate predicate, final Pageable pageable, final Sort... sorts) { return jdbcTemplate.execute(new ConnectionCallback<Page<T>>(){ public Page<T> doInConnection(Connection con) throws SQLException, DataAccessException { SQLQuery query = new SQLQuery(con, dialect).from(metamodel); applyWhere(query, predicate); applySorting(query, sorts); applyPagination(query, pageable); List<T> content = query.list(metamodel); SQLQuery countQuery = new SQLQuery(con, dialect).from(metamodel); applyWhere(countQuery, predicate); long total = countQuery.count(); return new Pagination<T>(content, pageable, total); } }); }
@Override public Long execute() { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate.execute(new ConnectionCallback<Long>() { @Override public Long doInConnection(Connection connection) throws SQLException, DataAccessException { final SQLDeleteClause deleteClause = new SQLDeleteClause(connection, configuration, pathBase); for (BooleanExpression expression : QueryExampleHelper.getExpressions(pathBase, example)) { deleteClause.where(expression); } for (SQLBindings sqlBindings : deleteClause.getSQL()) { LOGGER.debug("SQL: {} \nparams: {}", sqlBindings.getSQL(), sqlBindings.getBindings()); } return deleteClause.execute(); } }); }
public synchronized void runScripts(Stream<String> scripts) { jdbcTemplate.execute((ConnectionCallback<Void>) connection -> { IBatisPatchedScriptRunner scriptRunner = new IBatisPatchedScriptRunner(connection); scriptRunner.setAutoCommit(false); scriptRunner.setStopOnError(true); scripts.forEach(script -> { logger.debug("Running script {}.", script); try (FileReader reader = new FileReader(script)) { scriptRunner.runScript(reader); } catch (IOException e) { throw new RuntimeSqlException(e); } }); return null; }); }
@Override protected void doHealthCheck(Health.Builder builder) throws Exception { log.debug("Initializing Database health indicator"); try { String dataBaseProductName = jdbcTemplate.execute(new ConnectionCallback<String>() { @Override public String doInConnection(Connection connection) throws SQLException, DataAccessException { return connection.getMetaData().getDatabaseProductName(); } }); query = detectQuery(dataBaseProductName); builder.up(); } catch (Exception e) { log.debug("Cannot connect to Database.", e); builder.down(e); } }
@Override public Result check() { try { String dataBaseProductName = this.jdbcTemplate.execute(new ConnectionCallback<String>() { @Override public String doInConnection(Connection connection) throws SQLException, DataAccessException { return connection.getMetaData().getDatabaseProductName(); } }); query = detectQuery(dataBaseProductName); return Result.healthy(dataBaseProductName); } catch (Exception e) { log.debug("Cannot connect to Database: {}", e); return Result.unhealthy("Cannot connect to Database : " + e.getMessage()); } }
public Table(final JdbcTemplate jdbcTemplate, final String name) { this.name = name; this.addAll(jdbcTemplate.query("SELECT * FROM " + name, new TableMapperResultSetExtractor())); primaryColumns = jdbcTemplate.execute(new ConnectionCallback<Set<String>>() { @Override public Set<String> doInConnection(final Connection connection) throws SQLException, DataAccessException { ResultSet rs = null; try { rs = connection.getMetaData().getPrimaryKeys(null, null, name); final Set<String> columns = Sets.newLinkedHashSet(); while (rs.next()) { columns.add(rs.getString("COLUMN_NAME").toLowerCase()); } return Collections.unmodifiableSet(columns); } finally { JdbcUtils.closeResultSet(rs); } } }); }
@Override protected Result check() throws Exception { log.debug("Initializing Database health indicator"); try { String dataBaseProductName = jdbcTemplate.execute(new ConnectionCallback<String>() { @Override public String doInConnection(Connection connection) throws SQLException, DataAccessException { return connection.getMetaData().getDatabaseProductName(); } }); query = detectQuery(dataBaseProductName); return healthy(); } catch (Exception e) { log.debug("Cannot connect to Database.", e); return unhealthy("Cannot connect to database.", e); } }
private SupportSequenceDb validateDb(String datasourceName) { return this.getJdbcTemplate(datasourceName).execute(new ConnectionCallback<SupportSequenceDb>() { public SupportSequenceDb doInConnection(Connection con) throws SQLException, DataAccessException { DatabaseMetaData databaseMetaData = con.getMetaData(); String databaseProductName = databaseMetaData.getDatabaseProductName(); if (org.apache.commons.lang.StringUtils.containsIgnoreCase(databaseProductName, SupportSequenceDb.oracle.name())) { return SupportSequenceDb.oracle; } else if (org.apache.commons.lang.StringUtils.containsIgnoreCase(databaseProductName, SupportSequenceDb.db2.name())) { return SupportSequenceDb.db2; } return null; } }); }
protected IDialect getDialect(JdbcTemplate jdbcTemplate){ return jdbcTemplate.execute(new ConnectionCallback<IDialect>(){ public IDialect doInConnection(Connection connection) throws SQLException, DataAccessException { IDialect result=null; for(IDialect dialect:dialects){ if(dialect.support(connection)){ result=dialect; break; } } return result; } }); }
/** * 返回就诶过 key:column name , value=index name */ public static Map<String/* column name */, String /* index name */> getTableIndex(final DataSource dataSource, final String schemaName, final String tableName) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return (Map<String, String>) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection conn) throws SQLException, DataAccessException { DatabaseMetaData metaData = conn.getMetaData(); String sName = getIdentifierName(schemaName, metaData); String tName = getIdentifierName(tableName, metaData); ResultSet rs = metaData.getIndexInfo(sName, sName, tName, false, true); Map<String, String> indexes = new HashMap<String, String>(); while (rs.next()) { String columnName = rs.getString(9); String indexName = rs.getString(6); if (columnName != null && indexName != null) { indexes.put(columnName, indexName); } } rs.close(); return indexes; } }); }
private void testConnection(DataSource dataSource) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String version = (String) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection con) throws SQLException, DataAccessException { DatabaseMetaData metaData = con.getMetaData(); return metaData.getDatabaseProductName() + "-" + metaData.getDatabaseProductVersion(); } }); System.out.println(version); Assert.assertNotNull(version); }
/** * 返回就诶过 key:column name , value=index name */ public static Map<String/* column name */, String /* index name */> getTableIndex(final DataSource dataSource, final String schemaName, final String tableName) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return (Map<String, String>) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection conn) throws SQLException, DataAccessException { DatabaseMetaData metaData = conn.getMetaData(); String sName = getIdentifierName(schemaName, metaData); String tName = getIdentifierName(tableName, metaData); ResultSet rs = null; Map<String, String> indexes; try { rs = metaData.getIndexInfo(sName, sName, tName, false, true); indexes = new HashMap<String, String>(); while (rs.next()) { String columnName = rs.getString(9); String indexName = rs.getString(6); if (columnName != null && indexName != null) { indexes.put(columnName, indexName); } } } finally { JdbcUtils.closeResultSet(rs); } return indexes; } }); }
private String getProduct() { return this.jdbcTemplate.execute(new ConnectionCallback<String>() { @Override public String doInConnection(Connection connection) throws SQLException, DataAccessException { return connection.getMetaData().getDatabaseProductName(); } }); }
@Test public void getPoolSizeNoConnection() { // Make sure the pool is initialized JdbcTemplate jdbcTemplate = new JdbcTemplate( getDataSourceMetadata().getDataSource()); jdbcTemplate.execute(new ConnectionCallback<Void>() { @Override public Void doInConnection(Connection connection) throws SQLException, DataAccessException { return null; } }); assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(0)); assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0)); }
@Override public void afterPropertiesSet() throws Exception { if (this.template == null) { this.template = new JdbcTemplate(datasource); } this.template.execute(new ConnectionCallback<Integer>() { @Override public Integer doInConnection(Connection con) throws SQLException, DataAccessException { ResultSet rs = null; Statement stmt = null; try { rs = con.getMetaData().getTables(null, null, "BLOBS", new String[] {"TABLE"}); if (!rs.next()) { logger.info("Creating JPA Content Repository"); stmt = datasource.getConnection().createStatement(); String sql = "CREATE TABLE BLOBS " + "(id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1), " + " blob BLOB, " + " PRIMARY KEY ( id ))"; return stmt.executeUpdate(sql); } } finally { if (stmt != null) { stmt.close(); } if (rs != null) { rs.close(); } } return null; } }); }
private void executeScript(Optional<String> databaseName, final String script) { JdbcTemplate jdbcTemplate = databaseName.isPresent() ? jdbcTemplate(databaseName.get()) : jdbcTemplate(); jdbcTemplate.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection con) throws SQLException, DataAccessException { ScriptUtils.executeSqlScript(con, new ClassPathResource(script)); return null; } }); }
@Test public void databaseIsIntializedTest() { JdbcTemplate template = new JdbcTemplate(ds); Set<String> wte4jTables = template.execute(new ConnectionCallback<Set<String>>() { @Override public Set<String> doInConnection(Connection con) throws SQLException, DataAccessException { Set<String> tableNames = new HashSet<String>(); ResultSet tableRs = con.getMetaData().getTables(null, null, null, new String[] { "TABLE" }); try { while (tableRs.next()) { tableNames.add(tableRs.getString("TABLE_NAME").toLowerCase()); } } finally { tableRs.close(); } return tableNames; } }); assertEquals(6, wte4jTables.size()); assertTrue(wte4jTables.contains("person")); assertTrue(wte4jTables.contains("purchase_order")); assertTrue(wte4jTables.contains("wte4j_template")); assertTrue(wte4jTables.contains("wte4j_template_properties")); assertTrue(wte4jTables.contains("wte4j_gen")); assertTrue(wte4jTables.contains("wte4j_template_content_mapping")); }