当前位置: 首页>>代码示例>>Java>>正文


Java DataSource类代码示例

本文整理汇总了Java中javax.sql.DataSource的典型用法代码示例。如果您正苦于以下问题:Java DataSource类的具体用法?Java DataSource怎么用?Java DataSource使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DataSource类属于javax.sql包,在下文中一共展示了DataSource类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testConnectionsWithTx

import javax.sql.DataSource; //导入依赖的package包/类
@Test
public void testConnectionsWithTx() throws Exception {
    DataSource ds = wrap(createHsqlDataSource());

    Transaction tx = tm.begin();
    try {
        try (Connection con = ds.getConnection()) {
            try (Connection con2 = ds.getConnection()) {
                assertNotSame(con, con2);
            }
        }
        tx.commit();
    } catch (Throwable t) {
        tx.rollback();
        throw t;
    }
}
 
开发者ID:ops4j,项目名称:org.ops4j.pax.transx,代码行数:18,代码来源:HsqlTest.java

示例2: collectDBPoolMetrics

import javax.sql.DataSource; //导入依赖的package包/类
@Override
protected void collectDBPoolMetrics(MonitorElement clientElem) {

    if (this.datasources.size() == 0) {
        return;
    }

    for (DataSource cp : this.datasources) {
        String jdbcURL = (String) ReflectionHelper.invoke(cp.getClass().getName(), cp, "getUrl", null, null,
                cp.getClass().getClassLoader());

        MonitorElementInstance inst = this.matchElemInstance(clientElem, jdbcURL);

        if (inst == null) {
            continue;
        }

        collectDataSourceStat(inst, cp, webapploaderForMybatis);
    }
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:21,代码来源:MybatisHookProxy.java

示例3: preCreate

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * 扩展功能,可以自定义一些自己实现的 dataSource
 */
private DataSource preCreate(Long pipelineId, DbMediaSource dbMediaSource) {

    if (CollectionUtils.isEmpty(dataSourceHandlers)) {
        return null;
    }

    DataSource dataSource = null;
    for (DataSourceHanlder handler : dataSourceHandlers) {
        if (handler.support(dbMediaSource)) {
            dataSource = handler.create(pipelineId, dbMediaSource);
            if (dataSource != null) {
                return dataSource;
            }
        }
    }
    return null;
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:21,代码来源:DataSourceCreator.java

示例4: dataSource

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * The following bean configures the database connection. The 'url' property value of "jdbc:derby:directory:jpaserver_derby_files;create=true" indicates that the server should save resources in a
 * directory called "jpaserver_derby_files".
 * 
 * A URL to a remote database could also be placed here, along with login credentials and other properties supported by BasicDataSource.
 */
@Bean(destroyMethod = "close")
public DataSource dataSource() {
	BasicDataSource retVal = new BasicDataSource();
	/*
	retVal.setDriver(new org.apache.derby.jdbc.EmbeddedDriver());
	retVal.setUrl("jdbc:derby:directory:target/jpaserver_derby_files;create=true");
	retVal.setUsername("");
	retVal.setPassword("");
	* */
	 
	
	try
	{
		retVal.setDriver(new com.mysql.jdbc.Driver());
	}
	catch (Exception exc)
	{
		exc.printStackTrace();
	}
	retVal.setUrl("jdbc:mysql://localhost:3306/dhis2_fhir");
	retVal.setUsername("root");
	retVal.setPassword("");
	return retVal;
}
 
开发者ID:gerard-bisama,项目名称:DHIS2-fhir-lab-app,代码行数:31,代码来源:FhirServerConfigDstu3.java

示例5: clusterSqlSessionFactory

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * SqlSessionFactory配置
 *
 * @return
 * @throws Exception
 */
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(
        @Qualifier("clusterDataSource") DataSource dataSource
) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    //配置mapper文件位置
    sqlSessionFactoryBean.setMapperLocations(resolver.getResources(clusterMapperLocations));

    //配置分页插件
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("reasonable", "true");
    properties.setProperty("supportMethodsArguments", "true");
    properties.setProperty("returnPageInfo", "check");
    properties.setProperty("params", "count=countSql");
    pageHelper.setProperties(properties);

    //设置插件
    sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
    return sqlSessionFactoryBean.getObject();
}
 
开发者ID:Lengchuan,项目名称:SpringBoot-Study,代码行数:31,代码来源:ClusterDruidDataSourceConfig.java

示例6: updateDatabaseSchema

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * Execute schema update script, determined by the Configuration object
 * used for creating the SessionFactory. A replacement for Hibernate's
 * SchemaUpdate class, for automatically executing schema update scripts
 * on application startup. Can also be invoked manually.
 * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
 * SessionFactory to be able to invoke this method, e.g. via
 * {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");}.
 * <p>Uses the SessionFactory that this bean generates for accessing a
 * JDBC connection to perform the script.
 * @throws DataAccessException in case of script execution errors
 * @see #setSchemaUpdate
 * @see org.hibernate.cfg.Configuration#generateSchemaUpdateScript
 * @see org.hibernate.tool.hbm2ddl.SchemaUpdate
 */
public void updateDatabaseSchema() throws DataAccessException {
	logger.info("Updating database schema for Hibernate SessionFactory");
	DataSource dataSource = getDataSource();
	if (dataSource != null) {
		// Make given DataSource available for the schema update.
		configTimeDataSourceHolder.set(dataSource);
	}
	try {
		SessionFactory sessionFactory = getSessionFactory();
		final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
		HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
		hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER);
		hibernateTemplate.execute(
			new HibernateCallback<Object>() {
				@Override
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					@SuppressWarnings("deprecation")
					Connection con = session.connection();
					DatabaseMetadata metadata = new DatabaseMetadata(con, dialect);
					String[] sql = getConfiguration().generateSchemaUpdateScript(dialect, metadata);
					executeSchemaScript(con, sql);
					return null;
				}
			}
		);
	}
	finally {
		if (dataSource != null) {
			configTimeDataSourceHolder.remove();
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:48,代码来源:LocalSessionFactoryBean.java

示例7: multiTenantLiquibase

import javax.sql.DataSource; //导入依赖的package包/类
@Bean
@DependsOn("liquibase")
public MultiTenantSpringLiquibase multiTenantLiquibase(
    DataSource dataSource,
    LiquibaseProperties liquibaseProperties) {
    MultiTenantSpringLiquibase liquibase = new XmMultiTenantSpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog(CHANGE_LOG_PATH);
    liquibase.setContexts(liquibaseProperties.getContexts());
    liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
    liquibase.setDropFirst(liquibaseProperties.isDropFirst());
    liquibase.setSchemas(getSchemas());
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) {
        liquibase.setShouldRun(false);
    } else {
        liquibase.setShouldRun(liquibaseProperties.isEnabled());
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
 
开发者ID:xm-online,项目名称:xm-ms-balance,代码行数:21,代码来源:DatabaseConfiguration.java

示例8: doReleaseConnection

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * Actually close the given Connection, obtained from the given DataSource.
 * Same as {@link #releaseConnection}, but throwing the original SQLException.
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param con the Connection to close if necessary
 * (if this is {@code null}, the call will be ignored)
 * @param dataSource the DataSource that the Connection was obtained from
 * (may be {@code null})
 * @throws SQLException if thrown by JDBC methods
 * @see #doGetConnection
 */
public static void doReleaseConnection(Connection con, DataSource dataSource) throws SQLException {
	if (con == null) {
		return;
	}
	if (dataSource != null) {
		ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
		if (conHolder != null && connectionEquals(conHolder, con)) {
			// It's the transactional Connection: Don't close it.
			conHolder.released();
			return;
		}
	}
	logger.debug("Returning JDBC Connection to DataSource");
	doCloseConnection(con, dataSource);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:27,代码来源:DataSourceUtils.java

示例9: dynamicSqlSessionFactory

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * Dynamic sql session factory sql session factory.
 *
 * @param dynamicDataSource the dynamic data source
 * @param properties        the properties
 * @return the sql session factory
 */
@Bean
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public SqlSessionFactory dynamicSqlSessionFactory(
		@Qualifier("dynamicDataSource") DataSource dynamicDataSource,
		MybatisProperties properties) {
	final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
	sessionFactory.setDataSource(dynamicDataSource);
	sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(properties.getConfigLocation()));
	sessionFactory.setMapperLocations(properties.resolveMapperLocations());
	try {
		return sessionFactory.getObject();
	} catch (Exception e) {
		throw new SystemException(e);
	}
}
 
开发者ID:ruyangit,项目名称:angit,代码行数:23,代码来源:DatasourceConfig.java

示例10: getNewDataSource

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * 获取新的数据源
 *
 * @return
 */
public static DataSource getNewDataSource() {
    if (newDataSource == null) synchronized (TaleUtils.class) {
        if (newDataSource == null) {
            Properties properties = TaleUtils.getPropFromFile("application-default.properties");
            if (properties.size() == 0) {
                return newDataSource;
            }
            DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
            managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
            String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            managerDataSource.setUrl(str);
            managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
            newDataSource = managerDataSource;
        }
    }
    return newDataSource;
}
 
开发者ID:ZHENFENG13,项目名称:My-Blog,代码行数:24,代码来源:TaleUtils.java

示例11: dataSource

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * Embedded H2 database
 * Connect to running database with the following details:
 *
 * URL: jdbc:h2:mem:dataSource
 * Driver Class: org.h2.Driver
 * Username: sa
 * Password: [blank]
 *
 * @return
 */
@Bean
public DataSource dataSource() {
    final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    database = builder.setType(EmbeddedDatabaseType.H2)
            .setName("dataSource")
            .ignoreFailedDrops(true)
            .continueOnError(false)
            .addScript("classpath:database/h2/calendar-schema.sql")
            .addScript("classpath:database/h2/calendar-data.sql")
            .build();
    return database;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:24,代码来源:DataSourceConfig.java

示例12: masterDataSource

import javax.sql.DataSource; //导入依赖的package包/类
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    return dataSource;
}
 
开发者ID:zcc225,项目名称:springboot-copy,代码行数:11,代码来源:MasterDataSourceConfig.java

示例13: entityManagerFactory

import javax.sql.DataSource; //导入依赖的package包/类
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory(DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
	emf.setPackagesToScan("com.exmaple.test.entities");
	return emf;
}
 
开发者ID:holon-platform,项目名称:holon-datastore-jpa,代码行数:9,代码来源:ExampleJpaDatastoreSpring.java

示例14: checkTransactionStatus

import javax.sql.DataSource; //导入依赖的package包/类
@Override
public Boolean checkTransactionStatus(String appId, String busCode, String trxId) {
	
	DataSource dataSource = selctor.selectDataSource(appId, busCode, trxId);
	JdbcTemplate jdbcTemplate = getJdbcTemplate(dataSource);
	
	//select * for update
	List<Integer> statusList = jdbcTemplate.queryForList("select status from executed_trans where app_id = ? and bus_code = ? and trx_id = ? for update;", new Object[]{appId,busCode,trxId}, Integer.class);
	
	if(statusList == null || statusList.size() == 0) {
		return false;
	} else {
		//it can only be 1 record,because it's search by primary key
		int status = statusList.get(0);
		
		switch(status){
		case TransactionStatus.UNKNOWN:
			//parent transaction status unknown
			return null;
		case TransactionStatus.COMMITTED:
			//success
			return true;
		case TransactionStatus.ROLLBACKED:
			return false;
		default:
			throw new IllegalArgumentException("unknown transaction status:" + status);
		}
	}
}
 
开发者ID:QNJR-GROUP,项目名称:EasyTransaction,代码行数:30,代码来源:DefaultTransStatusLoggerImpl.java

示例15: getSimpleData

import javax.sql.DataSource; //导入依赖的package包/类
/**
 * Return a simple export data without any computation.
 * 
 * @param subscription
 *            The subscription identifier.
 * @return the SLA configuration
 */
protected JiraSimpleExport getSimpleData(final int subscription) {

	// Find the project corresponding to the given JIRA project
	final long start = System.currentTimeMillis();
	final Map<String, String> parameters = subscriptionResource.getParameters(subscription);
	final int jira = Integer.parseInt(parameters.get(JiraBaseResource.PARAMETER_PROJECT));
	final String pkey = parameters.get(JiraBaseResource.PARAMETER_PKEY);
	final DataSource dataSource = getDataSource(parameters);

	// Get issues of this project
	log.info("Get issues of {}({})", pkey, jira);
	final List<JiraIssueRow> issues = jiraDao.getIssues(dataSource, jira, pkey);
	log.info("Retrieved changes : {}", issues.size());

	final Map<Integer, String> statusText = jiraDao.getStatuses(dataSource);
	final Map<Integer, String> priorityText = jiraDao.getPriorities(dataSource);
	final Map<Integer, String> resolutionText = jiraDao.getResolutions(dataSource);
	final Map<Integer, String> typeText = jiraDao.getTypes(dataSource, jira);
	log.info("Fetch done of {} for {} issues, {} status, {} priorities, {} types, {} resolutions", subscription,
			issues.size(), statusText.size(), priorityText.size(), typeText.size(), resolutionText.size());

	final JiraSimpleExport jiraComputations = new JiraSimpleExport();
	jiraComputations.setIssues(issues);
	jiraComputations.setStatusText(statusText);
	jiraComputations.setPriorityText(priorityText);
	jiraComputations.setResolutionText(resolutionText);
	jiraComputations.setTypeText(typeText);
	log.info("End of simple export, took {}",
			DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));
	return jiraComputations;
}
 
开发者ID:ligoj,项目名称:plugin-bt-jira,代码行数:39,代码来源:JiraExportPluginResource.java


注:本文中的javax.sql.DataSource类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。