【问题标题】:Spring Hibernate: Identify which database connectionSpring Hibernate:识别哪个数据库连接
【发布时间】:2017-02-23 11:07:31
【问题描述】:

注意:我知道我可以使用脚本或数据库字段来解决此问题,但我对访问连接字符串感到好奇。

我有两个测试环境。每个都有自己的数据库,一个是中文的,一个是英文的。否则这两个数据库是相同的。

唯一的区别是我的 beans.xml 中的连接字符串(ctest vs ctestzh)。

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="org.postgresql.Driver" />
		<property name="jdbcUrl" value="jdbc:postgresql://localhost/ctest?useUnicode=true&#38;characterEncoding=utf8" />
		<property name="user" value="testuser" />
		<property name="password" value="xxxx" />
....
	</bean>

	<!-- Hibernate 
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="org.postgresql.Driver" />
		<property name="jdbcUrl" value="jdbc:postgresql://localhost/ctestzh?useUnicode=true&#38;characterEncoding=utf8" />
		<property name="user" value="testuser" />
		<property name="password" value="xxxx" />
.....
	</bean>-->

我使用 xml 配置文件将我的应用程序配置为处理英文或中文数据。但是,如果忘记将 beans.xml 更改为适当的数据,则会损坏数据库(即将中文数据放入英文数据库)

我可以访问代码中的连接字符串,以便在连接到错误的数据库时失败吗?我看过 SessionFactory,但没有看到任何明显的东西。

【问题讨论】:

    标签: spring hibernate


    【解决方案1】:
    public String getConnectionString(DataSource dataSource) {
      return dataSource.getConnection().getMetaData().getURL();
    }
    

    请参阅DatabaseMetaData class 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2010-12-27
      • 2015-06-11
      • 2010-11-06
      相关资源
      最近更新 更多