Spring Hibernate: Identify which database connection - spring

NOTE: I know I can fix this using scripts or a database field, but I am curious about accessing the connection string.
I have two testing environments. Each has its own database, one for Chinese and one for English data. Otherwise the two databases are identical.
The only difference is the connection string in my 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&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&characterEncoding=utf8" />
<property name="user" value="testuser" />
<property name="password" value="xxxx" />
.....
</bean>-->
I use an xml configuration file that configures my application to either process English or Chinese data. If I forget to change the beans.xml to the appropriate data, however, I corrupt the database (i.e., put Chinese data in the English database)
Can I access the connection string in code so I can fail if I am connected to the wrong database? I have looked at SessionFactory, but saw nothing obvious.

public String getConnectionString(DataSource dataSource) {
return dataSource.getConnection().getMetaData().getURL();
}
See DatabaseMetaData class for more info.

Related

Spring JDBC Extensions, Oracle AQ, ClassCastException on listening to queue

(I hope this below makes sense, I had a bit of a struggle with formatting).
We have an application (currently being refreshed from technology of circa 2005) whose owners require the use of Oracle AQ for message handling.
We are using the Spring JDBC extensions, and when the application begins to listen to the queue it gets a ClassCastException saying "X cannot be cast to oracle.jdbc.internal.OracleConnection".
Where X is either a WrappedConnectionJDK7 from jboss when we use a datasource defined in Wildfly e.g.
<bean id="dataSource-supsrep"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE" />
<property name="username" value="...." />
<property name="password" value="...." />
</bean>
or X is a PoolGuardConnectionWrapper from commons.dbcp when we define the datasource like this:
<bean id="dataSource-supsrep"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE" />
<property name="username" value="...." />
<property name="password" value="...." />
</bean>
Message Listener bean is defined like this :
<bean id="messageListener" class="xxx.report.dispatch.DispatchMDB" />
Message Listener container bean is like this :
<bean id="reportProcessorXslfoHigh"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="sessionTransacted" value="true" />
<property name="connectionFactory" ref="AQconnectionFactory" />
<property name="destinationName" value="Q1_XSLFO_HIGH" />
<property name="messageListener" ref="messageListener" />
<property name="transactionManager" ref="transactionManager" />
<property name="concurrentConsumers" value="1" />
<property name="maxConcurrentConsumers" value="1" />
<property name="receiveTimeout" value="30000" />
<property name="idleTaskExecutionLimit" value="30" />
<property name="idleConsumerLimit" value="1" />
</bean>
The connection factory is like this :
<orcl:aq-jms-connection-factory id="AQconnectionFactory"
data-source="dataSource-supsrep" native-jdbc- extractor="oracleNativeJdbcExtractor" />
and it uses a Native JDBC Extractor :
<bean id="oracleNativeJdbcExtractor"
class="org.springframework.jdbc.support
.nativejdbc.OracleJdbc4NativeJdbcExtractor" />
So my question is - can this be overcome by Spring configuration details - or is there another way round it? Clearly the underlying connection is needed but after 3 days of research I cannot see how it can be done.
Any clues gratefully received !
Thanks,
John

Hibernate c3p0 and Spring. Invalid property 'driverClassName' of bean class [org.hibernate.c3p0.internal.C3P0ConnectionProvider]

I'm currently developing an application that uses hibernate and Spring MVC.
I want to implement c3p0 but I can't understand how to implement it.
I used the c3p0 jars in the optional folder, Hibernate-c3p0-5.0.2.jar and
c3p0-0.9.2.1.jar.
These are my configurations.
Right now, I'm using DriverManagerDatasource from Spring.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
I tried doing this
<bean id="dataSource" class="org.hibernate.c3p0.internal.C3P0ConnectionProvider">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- C3P0 Config -->
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="100" />
<property name="hibernate.c3p0.max_size" value="10" />
<property name="hibernate.c3p0.max_statements" value="10" />
<property name="hibernate.c3p0.min_size" value="10" />
<property name="hibernate.c3p0.timeout" value="100" />
</bean>
but i'm getting an error.
Invalid property 'driverClassName' of bean class [org.hibernate.c3p0.internal.C3P0ConnectionProvider]
TIA.
driverClassName is a DriverManagerDataSource property, not a property on the C3P0ConnectionProvider. So that's why you're getting the error.
Instead of using the Spring DriverManagerDataSource, which is just a simple DataSource implementation and not a connection pool at all, you want to use C3P0's DataSource implementation. Try using ComboPooledDataSource. That implementation also has a driverClassName property, which you will want to set equal to your database driver (like MySQL driver or whatever).
Here's an example that I lifted off a web page:
cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
cpds.setJdbcUrl("jdbc:mysql://localhost/test");
cpds.setUser("root");
cpds.setPassword("root");
That's not Spring, but just make the adjustment to put it in Spring. The full class name is com.mchange.v2.c3p0.ComboPooledDataSource. You can see a Spring-based example here.
i know this question is old but for the newbies, hope it helps.
The problem is with your name tags
replace:
<bean id="dataSource" class="org.hibernate.c3p0.internal.C3P0ConnectionProvider">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
with
<bean id="dataSource" class="org.hibernate.c3p0.internal.C3P0ConnectionProvider">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
...
Please note: driverClass is used instead of driverClassName, jdbcUrl is used instead of url, user is used instead of username and password is at it was..... these are the parameters for ComboPooledDataSource
HOPE IT HELPS

Can we use DBCP 2 or Tomcat connection pool for distributed transactions in Spring? Can these connection pool be used along with JOTM or Atomikos?

Initially i was using different transaction manager for multiple data sources. But i had problem with managing rollback on all data sources if one of the data sources has transaction failure.I want to manage multiple datasources with single Transaction manager in Spring. So i opted for using JOTM or Atomikos. Both these transaction manager uses XA Connection pool(org.enhydra.jdbc.pool.StandardXAPoolDataSource). But in my project i was allowed to use only DBCP 2(org.apache.commons.dbcp.BasicDataSource) or Tomcat Connection Pool(org.apache.tomcat.jdbc.pool.DataSource). Is it possible to use either of this connection pools with JOTM or Atomikos. Please someone help me on this along with configuration example. Below is my configuration details,
<
bean id="jotm" class="org.springframework.transaction.jta.JotmFactoryBean"/>
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="userTransaction" ref="jotm" />
</bean>
<bean id="dataSource1" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown">
<property name="dataSource">
<bean class ="org.enhydra.jdbc.standard.StandardXADataSource " destroy-method ="shutdown">
<property name="transactionManager" ref="jotm" />
<property name="driverName" value="${jdbc.d1.driver}" />
<property name ="url" value = "${jdbc.d1.url}" />
</bean>
</property>
<property name="user" value="${jdbc.d1.username}" />
<property name = "password" value="${jdbc.d1.password}" />
</bean>
<bean id="dataSource2" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown">
<property name="dataSource">
<bean class ="org. enhydra.jdbc.standard.StandardXADataSource " destroy-method ="shutdown">
<property name="transactionManager" ref="jotm" />
<property name="driverName" value="${jdbc.d2.driver}" />
<property name="url" value="${jdbc.d2.url}" />
</bean>
</property>
<property name="user" value="${jdbc.d2.username}" />
<property name = "password" value ="${jdbc.d2.password}" />
</bean>
Also do help if any other possible ways to achieve this.

Dynamically (Runtime) change Datasource credentials in Spring Mybatis

I want to dynamically change Datasource properties in Spring+MyBatis project.
Problem is in Spring + MyBatis integration, we cannot set the datasource properties dynamically during runtime.
Currently I'm using the following code to set the credentials:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
I tried options with UserCredentialsDataSourceAdapter to change the password during runtime but I cannot return back the dataSource object to use for the connection as MyBatis
ApplicationContext context = ApplicationContextUtils.getApplicationContext();
UserCredentialsDataSourceAdapter ds = (UserCredentialsDataSourceAdapter) context.getBean("dataSource");
ds.setCredentialsForCurrentThread("test", "test");
I'm stuck here, I cannot use the dataSource element ds to use for making connection for MyBatis. Please help me in resolving this issue.
I suppose that you use mybatis-spring.
Your approach with UserCredentialsDataSourceAdapter is not working because you are using connection pool, so connection is not closed after usage but are returned to the pool and reused later even that you've changed username and password.
To fix this just get rid of pool:
<bean id="targetDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
<property name="targetDataSource" ref="targetDataSource"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
and use the later bean in SqlSessionFactoryBean configuration:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
If you do not use mybatis-spring and use mybatis directly then the problem is to make mybatis use configured DataSource. This can be done by registering dataSource in JNDI and configure mybatis to get DataSource from JNDI.
<bean id="targetDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${app.jdbc.driverClassName}" />
<property name="url" value="${app.jdbc.url}" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
<property name="targetDataSource" ref="targetDataSource" />
<property name="username" value="#{app.jdbc.username}" />
<property name="password" value="#{app.jdbc.password}" />
</bean>
<!-- Declare a transaction manager for Encounter Navigator Authenticator -->
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- define the SqlSessionFactory for Encounter Navigator Authenticator,
notice that configLocation is not needed when you use MapperFactoryBean -->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
name="sqlSessionFactory">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations"
value="file:C:/Program Files/Apache Software Foundation/Tomcat 7.0/config/app_user/*.xml" />
<property name="configLocation" value="classpath:sqlmap-config.xml" />
</bean>
<!-- scan for MAPPERS and let them be auto-wired - For Encounter Navigator
Authenticator -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage"
value="com.upmc.health.encounternavigator.dao.authentication" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
UserCredentialsDataSourceAdapter ds = (UserCredentialsDataSourceAdapter) applicationContext.getBean("dataSource");
ds.removeCredentialsFromCurrentThread();
ds.setCredentialsForCurrentThread("test", "test");
ds.setUsername("test");
ds.setPassword("test");
ds.setTargetDataSource(ds);
ds.afterPropertiesSet();
authDao.getDetails(); //This calls an interface and executes the query present in the xml file

How to get spring bean reference to java field automatically

my spring XML is below,
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
I'm creating the spring bean context when the server is starting up. When I hit on the submit button of the JSP page, it should call the servlet and executes the SQL Query.
Without doing JdbcTemplate jTemplate = (JdbcTemplate)context.getBean("jTemplate") is there anyway I can get the jTemplate object automatically injected to my java property?
my java property is this,
private JdbcTemplate jTemplate;
So, simply I want to use the jTemplate without just doing JdbcTemplate jTemplate = (JdbcTemplate)context.getBean("jTemplate")
Sorry guys I'm bit new to Spring, If you don't get what I'm saying please ask me again.
Use autowiring which can be in three ways
By name
By Type
By Constructor
Further reading is available here
like one solution is
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" autowire="byName">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean name="jTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
Use #Autowired annotation to get this bean automatically like this.
#Autowired
private JdbcTemplate jTemplate;

Resources