Java Code Examples for org.springframework.boot.jdbc.DataSourceBuilder

The following examples show how to use org.springframework.boot.jdbc.DataSourceBuilder. These examples are extracted from open source projects. 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
@Bean(name = "myBatisDataSource")
    @Primary
    @ConfigurationProperties(prefix = "data-source.single-db")
    public DataSource userDataSource() throws IOException, SQLException {
        if(!useMasterSlaveDataSource) {
            logger.info("-------------------- singleDB DataSource init ---------------------");
            return DataSourceBuilder.create().build();
        }else {
            logger.info("-------------------- masterSlave DataSource init ---------------------");
//            DataSource dataSource = YamlMasterSlaveDataSourceFactory.createDataSource(new File(
//                    DataSourceConfiguration.class.getResource("/META-INF/yamlMasterSlave.yaml").getFile()));
//            return dataSource;
            return null == masterSlaveProperties.getMasterDataSourceName()
                    ? ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingProperties.getShardingRuleConfiguration(), configMapProperties.getConfigMap(), propMapProperties.getProps())
                    : MasterSlaveDataSourceFactory.createDataSource(
                    dataSourceMap, masterSlaveProperties.getMasterSlaveRuleConfiguration(), configMapProperties.getConfigMap(), propMapProperties.getProps());
        }
    }
 
Example 2
Source Project: java-trader   Source File: TraderMainConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name="dataSource")
public DataSource dataSource() throws Exception
{
    //先试着用remote方式连接
    String url = detectRepositoryURL();
    String usr = "sa";
    String pwd = "";
    if ( url==null ) {
        logger.error("Connect to repository database failed");
        throw new Exception("Connect to repository database failed");
    }
    logger.info("Connect to H2 repository database in "+(url.indexOf("tcp")>0?"remote":"local")+" mode: "+url);

    DataSource ds = DataSourceBuilder.create()
        .driverClassName("org.h2.Driver")
        .url(url)
        .username(usr)
        .password(pwd)
        .build();
    ;
    return ds;
}
 
Example 3
private void runScripts(List<Resource> resources, String username, String password) {
    if (resources.isEmpty()) {
        return;
    }
    boolean continueOnError = Boolean.parseBoolean(getProperty("continue-on-error"));
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(continueOnError);
    populator.setSeparator(getProperty("seperator"));

    if (getProperty("sql-script-encoding") != null) {
        populator.setSqlScriptEncoding(getProperty("sql-script-encoding"));
    }
    for (Resource resource : resources) {
        populator.addScript(resource);
    }
    DataSource dataSource = this.dataSource;
    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        String driver = getProperty("driver-class-name");
        String url = getProperty("url");
        dataSource = DataSourceBuilder.create(this.getClass().getClassLoader()).driverClassName(driver).url(url)
                .username(username).password(password).build();
    }
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 4
public DataSource toDataSource() {
  DataSource dataSource;

  if (url == null || url.contains("hsqldb:mem")) {
    log.debug("Creating in memory HSQL database");
    // Start an in-process, in-memory HSQL server
    dataSource = new EmbeddedDatabaseBuilder().setType(HSQL).setName("c2mondb").build();
  } else {
    log.debug("Creating HSQL database at URL {}",url);
    dataSource = DataSourceBuilder.create().url(url).username(username).password(password).build();
  }

  if (!scripts.isEmpty()) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(scripts.toArray(new Resource[scripts.size()]));
    populator.setContinueOnError(true);
    DatabasePopulatorUtils.execute(populator, dataSource);
  }

  return dataSource;
}
 
Example 5
Source Project: beihu-boot   Source File: ApiBootBasicDataSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * create default basic data source
 *
 * @return DataSource
 * @throws RuntimeException 异常信息
 */
@Override
public DataSource build() throws RuntimeException {
    try {
        DataSource dataSource = DataSourceBuilder.create().url(config.getUrl()).username(config.getUsername()).password(config.getPassword()).driverClassName(config.getDriverClassName())
                // springboot 2.x default is HikariDataSource
                .type(HikariDataSource.class)
                .build();
        return dataSource;
    } catch (Exception e) {
        throw new RuntimeException("Create a default data source exception", e);
    }

}
 
Example 6
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    // 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
    return DataSourceBuilder.create().build();
}
 
Example 7
Source Project: txle   Source File: PrimaryConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDatasource() {
    return DataSourceBuilder.create().build();
}
 
Example 8
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    // 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
    return DataSourceBuilder.create().build();
}
 
Example 9
Source Project: springboot-link-admin   Source File: DataSourceConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "baseDataSource")
@Qualifier("baseDataSource")
@ConfigurationProperties(prefix = "spring.datasource.base")
@Primary
public DataSource primaryDataSource() {
	return DataSourceBuilder.create().build();
}
 
Example 10
Source Project: api-boot   Source File: ApiBootBasicDataSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * create default basic data source
 *
 * @return {@link DataSource} instance
 * @throws ApiBootException ApiBoot Exception
 */
@Override
public DataSource build() throws ApiBootException {
    try {
        DataSource dataSource = DataSourceBuilder.create().url(config.getUrl()).username(config.getUsername()).password(config.getPassword()).driverClassName(config.getDriverClassName())
            // springboot 2.x default is HikariDataSource
            .type(HikariDataSource.class)
            .build();
        return dataSource;
    } catch (Exception e) {
        throw new ApiBootException("Create a default data source exception", e);
    }

}
 
Example 11
Source Project: freeacs   Source File: DataSourceConfig.java    License: MIT License 5 votes vote down vote up
@Bean
@Primary
@Qualifier("main")
@ConfigurationProperties("main.datasource")
public DataSource mainDs() {
  return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
 
Example 12
/**
 * 通过Spring JDBC 快速创建 DataSource
 * @return
 */
@Bean(name = "masterDataSource")
@Qualifier("masterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
    return DataSourceBuilder.create().build();
}
 
Example 13
Source Project: springboot-guide   Source File: DataSource1Config.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 生成数据源.  @Primary 注解声明为默认数据源
 */
@Bean(name = "db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.hikari.db1")
@Primary
public DataSource testDataSource() {
    return DataSourceBuilder.create().build();
}
 
Example 14
Source Project: pandaria   Source File: DataSources.java    License: MIT License 5 votes vote down vote up
private DataSource buildDataSource(DatasourceProperties property) {
    return DataSourceBuilder.create()
            .driverClassName(property.getDriverClassName())
            .url(property.getUrl())
            .username(property.getUsername())
            .password(property.getPassword())
            .build();
}
 
Example 15
Source Project: multitenancy   Source File: MultiTenancyJpaConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds a map of all data sources defined in the application.yml file
 * 
 * @return
 */
@Primary
@Bean(name = "dataSourcesMtApp")
public Map<String, DataSource> dataSourcesMtApp() {
    Map<String, DataSource> result = new HashMap<>();
    for (DataSourceProperties dsProperties : this.multitenancyProperties.getDataSources()) {

        DataSourceBuilder factory = DataSourceBuilder.create().url(dsProperties.getUrl())
                .username(dsProperties.getUsername()).password(dsProperties.getPassword())
                .driverClassName(dsProperties.getDriverClassName());

        result.put(dsProperties.getTenantId(), factory.build());
    }
    return result;
}
 
Example 16
Source Project: x7   Source File: DataSourceConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Lazy
@Bean("readDataSource")
@ConfigurationProperties("spring.datasource.read")
public DataSource readDataSource() {
    DataSource dataSource = DataSourceBuilder.create().build();
    return dataSource;
}
 
Example 17
Source Project: tutorials   Source File: DataSourceConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName("org.h2.Driver");
    dataSourceBuilder.url("jdbc:h2:mem:test");
    dataSourceBuilder.username("SA");
    dataSourceBuilder.password("");
    return dataSourceBuilder.build();
}
 
Example 18
Source Project: dekorate   Source File: DatasourceConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
DataSource create() {
  return DataSourceBuilder.create()
    .username(username)
    .password(password)
    .url(uri.replaceAll("postgres", "jdbc:postgresql") + "/" + databaseName)
    .driverClassName("org.postgresql.Driver")
    .build();
}
 
Example 19
Source Project: danyuan-application   Source File: MultiDatasourceConfig.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
	public Map<String, DataSource> multiDatasource() {
		Map<String, DataSource> map = new HashMap<>();
		try {
			List<SysDbmsTabsJdbcInfo> list = sysDbmsTabsJdbcInfoDao.findAll();
			Class<DataSource> type = (Class<DataSource>) Class.forName("org.apache.tomcat.jdbc.pool.DataSource");
			for (SysDbmsTabsJdbcInfo sysZhcxAddr : list) {
				String driverClassName = "";
				String url = "";
				switch (sysZhcxAddr.getType()) {
					case "oracle":
						driverClassName = "oracle.jdbc.driver.OracleDriver";
						url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
						break;
					case "mysql":
//						driverClassName = "com.mysql.jdbc.Driver";
						driverClassName = "com.mysql.cj.jdbc.Driver";
						url = "jdbc:mysql://" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + "/" + sysZhcxAddr.getDatabaseName() + "?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true";
						break;
					default:
						driverClassName = "oracle.jdbc.driver.OracleDriver";
						url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
						break;
				}
				DataSource dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(sysZhcxAddr.getUsername()).password(sysZhcxAddr.getPassword()).type(type).build();

				map.put(sysZhcxAddr.getUuid(), dataSource);
			}
		} catch (ClassNotFoundException e) {
			logger.error("程序未发现jar包 《tomcat-jdbc》 ,springboot2之后默认数据源使用 “com.zaxxer.hikari.HikariDataSource”,使用其他数据源需要单独引入包", LogsClearScheduled.class);
		}
		return map;
	}
 
Example 20
Source Project: danyuan-application   Source File: MultiDatasourceConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws ClassNotFoundException
 * @方法名 getDataSource
 * @功能 TODO(这里用一句话描述这个方法的作用)
 * @参数 @param uuid
 * @参数 @return
 * @返回 DataSource
 * @author Administrator
 * @throws
 */
@SuppressWarnings("unchecked")
public DataSource getDataSource(String uuid) {
	Optional<SysDbmsTabsJdbcInfo> optional = sysDbmsTabsJdbcInfoDao.findById(uuid);
	if (optional.isPresent()) {
		try {
			SysDbmsTabsJdbcInfo sysZhcxAddr = optional.get();
			Class<DataSource> type = (Class<DataSource>) Class.forName("org.apache.tomcat.jdbc.pool.DataSource");
			String driverClassName = "";
			String url = "";
			switch (sysZhcxAddr.getType()) {
				case "oracle":
					driverClassName = "oracle.jdbc.driver.OracleDriver";
					url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
					break;
				case "mysql":
					// driverClassName = "com.mysql.jdbc.Driver";
					driverClassName = "com.mysql.cj.jdbc.Driver";
					url = "jdbc:mysql://" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + "/" + sysZhcxAddr.getDatabaseName() + "?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true";
					break;
				default:
					driverClassName = "oracle.jdbc.driver.OracleDriver";
					url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
					break;
			}
			return DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(sysZhcxAddr.getUsername()).password(sysZhcxAddr.getPassword()).type(type).build();
		} catch (ClassNotFoundException e) {
			logger.error("程序未发现jar包 《tomcat-jdbc》 ,springboot2之后默认数据源使用 “com.zaxxer.hikari.HikariDataSource”,使用其他数据源需要单独引入包", LogsClearScheduled.class);
		}
	}
	return null;
	
}
 
Example 21
Source Project: syndesis   Source File: DataSourceDefinition.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * create data source for the given Syndesis Data source
 * @return {@link TeiidDataSource}
 */
public TeiidDataSourceImpl createDatasource(String deploymentName, DefaultSyndesisDataSource scd) {
    DataSource ds = DataSourceBuilder.create().url(scd.getProperty("url"))
            .username(scd.getProperty("username") != null ? scd.getProperty("username")
                    : scd.getProperty("user"))
            .password(scd.getProperty("password")).build();

    if (ds instanceof HikariDataSource) {
        ((HikariDataSource)ds).setMaximumPoolSize(10);
        ((HikariDataSource)ds).setMinimumIdle(0);
        ((HikariDataSource)ds).setIdleTimeout(60000);
        ((HikariDataSource)ds).setScheduledExecutor(EXECUTOR);
    }
    Map<String, String> importProperties = new HashMap<String, String>();
    Map<String, String> translatorProperties = new HashMap<String, String>();

    if (scd.getProperty("schema") != null) {
        importProperties.put("importer.schemaName", scd.getProperty("schema"));
        importProperties.put("importer.UseFullSchemaName", "false");
    } else {
        //either we need to try the import and possibly fail,
        //or just start off with this as true and include the
        //the source schema names. for now this is simpler
        importProperties.put("importer.UseFullSchemaName", "true");
    }
    importProperties.put("importer.TableTypes", "TABLE,VIEW");
    importProperties.put("importer.UseQualifiedName", "true");
    importProperties.put("importer.UseCatalogName", "false");
    importProperties.put("importer.UseFullSchemaName", "false");

    TeiidDataSourceImpl teiidDS = new TeiidDataSourceImpl(scd.getSyndesisConnectionId(), deploymentName, getTranslatorName(), ds);
    teiidDS.setImportProperties(importProperties);
    teiidDS.setTranslatorProperties(translatorProperties);
    return teiidDS;
}
 
Example 22
Source Project: fish-admin   Source File: DataSourceConfig.java    License: MIT License 5 votes vote down vote up
@Primary
@Bean(name = "writeDataSource")
@Qualifier("writeDataSource")
@ConfigurationProperties(prefix = "spring.datasource.write")
public DataSource writeDataSource(){
    return DataSourceBuilder.create().build();
}
 
Example 23
Source Project: tutorials   Source File: DataSourceBean.java    License: MIT License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName("org.h2.Driver");
    dataSourceBuilder.url("jdbc:h2:mem:test");
    dataSourceBuilder.username("SA");
    dataSourceBuilder.password("");
    return dataSourceBuilder.build();
}
 
Example 24
@Override
public void onCreate(Organization organization, DataSourceInfo dataSourceInfo,
					 DataSourceBuilder<?> dataSourceBuilder) {

	if ("com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(dataSourceInfo.getDriverClassName())) {
		String url = dataSourceInfo.getUrl();
		if (!url.contains(databaseNameService.getDatabaseName(Constants.MASTER))) {
			String databaseName = databaseNameService.getDatabaseName(Constants.MASTER);
			url += "/" + databaseName;
			dataSourceBuilder.url(url);
		}
	}
}
 
Example 25
Source Project: multitenant   Source File: MysqlDataSourceCreateListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Organization organization, DataSourceInfo dataSourceInfo,
					 DataSourceBuilder<?> dataSourceBuilder) {
	if ("com.mysql.jdbc.Driver".equals(dataSourceInfo.getDriverClassName())) {
		String url = dataSourceInfo.getUrl();
		if (!url.contains(databaseNameService.getDatabaseName(Constants.MASTER))) {
			String databaseName = databaseNameService.getDatabaseName(Constants.MASTER);
			url += "/" + databaseName;
			dataSourceBuilder.url(url);
		}
	}
	
}
 
Example 26
Source Project: multitenant   Source File: DataSourceServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public DataSource createDataSource(Organization organization) {
	return MultitenantUtils.doQuery(() -> {
		DataSource dataSouce = null;
		DataSourceInfo dataSourceInfo = dataSourceInfoService.get(organization);
		if (StringUtils.isEmpty(dataSourceInfo.getJndiName())) {
			String master = Constants.MASTER;
			if (EmbeddedDatabaseConnection.isEmbedded(dataSourceInfo.getDriverClassName())) {
				master = properties.determineDatabaseName();
			}
			DataSourceBuilder<?> factory = this.properties.initializeDataSourceBuilder();
			factory.url(dataSourceInfo.getUrl().replace(databaseNameService.getDatabaseName(master), databaseNameService.getDatabaseName(organization.getId())))
				.username(dataSourceInfo.getUsername())
				.password(dataSourceInfo.getPassword());
			if (!StringUtils.isEmpty(dataSourceInfo.getDriverClassName())) {
				factory.driverClassName(dataSourceInfo.getDriverClassName());
			}
			if (!StringUtils.isEmpty(dataSourceInfo.getType())) {
				try {
					factory.type((Class<? extends DataSource>) Class.forName(dataSourceInfo.getType()));
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e.getMessage());
				}
			}
			publishEvent(organization, dataSourceInfo, factory);
			dataSouce = factory.build();
		} else {
			JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
			dataSouce = dataSourceLookup.getDataSource(dataSourceInfo.getJndiName());
		}
		dataSourceMap.put(organization.getId(), dataSouce);
		this.applicationContext.publishEvent(new OrgDataSourceCreateEvent(dataSouce));
		return dataSouce;
	});

}
 
Example 27
Source Project: multitenant   Source File: DataSourceServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void publishEvent(Organization organization, DataSourceInfo dataSourceInfo, DataSourceBuilder<?> dataSourceBuilder) {
	if (listeners != null) {
		for (DataSourceCreateListener dataSourceCreateListener : listeners) {
			dataSourceCreateListener.onCreate(organization, dataSourceInfo, dataSourceBuilder);
		}
	}
	
}
 
Example 28
Source Project: spring-boot-demo   Source File: DatasourceConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.type(DynamicDataSource.class);
    return dataSourceBuilder.build();
}
 
Example 29
Source Project: flowable-engine   Source File: DevelopmentConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public DataSource developmentDataSource() {
    return DataSourceBuilder
        .create()
        .driverClassName(DATASOURCE_DRIVER_CLASS_NAME)
        .url(DATASOURCE_URL)
        .username(DATASOURCE_USERNAME)
        .password(DATASOURCE_PASSWORD)
        .build();
}
 
Example 30
Source Project: flowable-engine   Source File: DevelopmentConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public DataSource developmentDataSource() {
    return DataSourceBuilder
        .create()
        .driverClassName(DATASOURCE_DRIVER_CLASS_NAME)
        .url(DATASOURCE_URL)
        .username(DATASOURCE_USERNAME)
        .password(DATASOURCE_PASSWORD)
        .build();
}