當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。