Reputation: 13
I have a Spring MVC + Hibernate + JPA app.
I hava a defaultPersistance
unit, that is defined in persistence.xml:
<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
<property name="hibernate.connection.url" value="jdbc:jtds:sqlserver://localhost:1433;databaseName=B3;" />
<property name="hibernate.connection.driver_class" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="hibernate.connection.username" value="hiber1" />
<property name="hibernate.connection.password" value="hiber1" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
I have an entityManagerFactory
and transactionManager
wired in mvc-dispatcher-servlet.xml:
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
So my question is: how can I change hibernate connection properties (eg. hibernate.connection. username) during runtime?
Upvotes: 1
Views: 915
Reputation: 52368
I would consider managing the datasource outside persistence.xml
and use UserCredentialsDataSourceAdapter
and its setCredentialsForCurrentThread
method.
Something around these lines:
<bean id="targetDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="jdbc:jtds:sqlserver://localhost:1433;databaseName=B3;" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
<property name="targetDataSource" ref="targetDataSource"/>
<property name="username" value="defaultUser"/>
<property name="password" value="mypassword" />
</bean>
And in your java code you would get a reference to dataSource
and call setCredentialsForCurrentThread(username, password)
. Every time the datasource has getConnection()
called on it, the credentials are checked against the current thread and those are used to get the connection.
Upvotes: 2