I have Spring JPA configuration as below
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<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>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="vendorAdaptor" />
<property name="packagesToScan" value="pk.training.model"/>
<property name="jpaProperties">
<props>
...
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
I have properties file in which i have password like
jdbc.password=abc123
When my application runs, spring context loads and makes connection to database. Fine. Now I want to ask suppose i give password in encrypted form, like
jdbc.password=$53ytg##!
Now how JPA connect to database ? Is there any property by which JPA handles encrypted password by itself or I have to do some thing on my own ?
Thanks.
You have to do this your own. Security wise, it doesn't add much, though. An attacker can
Set a breakpoint in Spring, wait until the bean is created and read the password from the field
Look at your code, find out where you store the key to decrypt the DB password, extract and use your code to decrypt it
Since most DB driver don't encrypt the data exchanged between your app and the database by default, your password (and all the data) is sent as plain text over the wire (unless the database is on the same server as your application).
So in most scenarios, the thing to do is to put the DB user and password in a file on your server's disk and make sure only authorized people can access this file (plus your app can read it). Encrypting the password only adds obscurity, no real security.
Related
I am developping a Spring MVC web application that use the dbcp database connection pool.
<bean id="datasourceAR_XXX" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
<property name="url"><value>jdbc:oracle:thin:#XXX.XXX.com:1500:SERVICE</value></property>
<property name="maxActive"><value>100</value></property>
<property name="maxIdle"><value>10</value></property>
<property name="username"><value>XXX</value></property>
<property name="password"><value>XXX</value></property>
</bean>
I recently moved the scope of those beans to singleton because the amount of connection per session started to be a bit too much.
The problem is :
Our database is shutting down every sunday and the spring application seems to act strangely by keeping the socket open and does not refresh the connection as I thought it would do.
Is there a way to refresh the beans scoped as singleton in a way that will refresh the connection everyday and not be obliged to relaunch the application every monday?
What you want to do is to configure validation for your connections. When a connection is borrowed from the pool you want to make sure that that connection is valid. For this you can specify the validationQuery property on your datasource.
<bean id="datasourceAR_XXX" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
<property name="url"><value>jdbc:oracle:thin:#XXX.XXX.com:1500:SERVICE</value></property>
<property name="maxActive"><value>100</value></property>
<property name="maxIdle"><value>10</value></property>
<property name="username"><value>XXX</value></property>
<property name="password"><value>XXX</value></property>
<property name="validationQuery" value="select 1 from dual" />
</bean>
See DBCP - validationQuery for different Databases for a list of possible validation queries for different databases.
There are some issues with Commons DBCP and it is pretty old (although there is a DBCP 2.x now). I would suggest moving to a different datasource like HikariCP this datasource is also a JDBC 4.x based datasource which allows for easier connection validation (it is part of the JDBC 4 spec).
<bean id="datasourceAR_XXX" class="com.zaxxer.hikari.HikariDataSource">
<property name="datasourceClassName" value="oracle.jdbc.pool.OracleDataSource"/>
<property name="maximumPoolSize" value="20" />
<property name="username" value="XXX" />
<property name="password" value="XXX" />
<property name="datasourceProperties">
<props>
<prop key="serverName">XXX.XXX.com</prop>
<prop key="port">1500</prop>
<prop key="databaseName">SERVICE</prop>
</props>
</property>
</bean>
If your oracle driver is new enough you don't need a validation query anymore as validation is provided by the driver instead of needing to be done with a query. Next to that you probably have better results with this pool.
Also you might have a bit of a large pool size, nice article/presentation about pool sizing can be found here.
I'm using Spring 3.* using JPA hibernate impl and I've set the Spring org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter generateDdl to true, but I don't see it actually doing anything. I swap it to false and I get the same output in my log. Anyone know what this setting is supposed to do? Its not generating the ddl.
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="api" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaProperties">
<props>
<prop key="hibernate.use_sql_comments">${jpa.vendor.showsql}</prop>
<prop key="hibernate.generate_statistics">${jpa.vendor.generate.statistics}</prop>
<prop key="hibernate.archive.autodetection">class</prop>
<prop key="hibernate.cache.use_second_level_cache">${cache.use.secondLevel}</prop>
<prop key="hibernate.cache.use_query_cache">${cache.use.query}</prop>
</props>
</property>
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${console.show.sql}" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
</bean>
If you use an IDE that has good Spring/XML support (notably IntelliJ IDEA), you can view what each property should do (in IDEA put the cursor on it and press CTRL+Q). The specc says:
Set whether to generate DDL after the EntityManagerFactory has been
initialized, creating/updating all relevant tables. Note that the
exact semantics of this flag depend on the underlying persistence
provider. For any more advanced needs, specify the appropriate
vendor-specific settings as "jpaProperties".
Having the value true means that if the database tables don't exist or need to be updated, it will be done automatically. If the value is false, you will have to do it manually.
I'm trying to configure a Hibernate SessionFactory using multi-tenancy options and with automatic schema creation, however i'm stuck on this error:
java.lang.NullPointerException
at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:52)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:367)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:304)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:293)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:498)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1742)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1780)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:242)
Here is my spring configuration:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource1"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
<prop key="hibernate.multiTenancy">DATABASE</prop>
<prop key="hibernate.multi_tenant_connection_provider">org.springframework.webflow.samples.booking.SampleMultiTenantConnectionProvider</prop>
<prop key="hibernate.tenant_identifier_resolver">org.springframework.webflow.samples.booking.SampleCurrentTenantIdentifierResolver</prop>
</props>
</property>
</bean>
<!-- Deploys a in-memory "booking" datasource populated -->
<bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:booking1" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:booking2" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
For now i'm using only DataSource 1, and the SampleConnectionProvider and TenantResolver always return the same tenant and datasource. However when Schema Export runs, it throws NullPointerException. The supplied ConnectionProvider to the SuppliedConnectionProviderHelper is null. It appears that he can't choose an appropriate ConnectionProvider when using multitenancy. The SuppliedConnectionProviderHelper is created on SchemaExport:
this.connectionHelper = new SuppliedConnectionProviderConnectionHelper(
serviceRegistry.getService( ConnectionProvider.class )
);
Can you use the hibernate.hbm2ddl.auto when using multitenancy? Already search in hibernate documentation but did not find anything.
Any help would be much appreciated!
Best regards
João Simas
It looks like there is no support for multi-tenancy in SchemaExport. I looked at source code in other places connection provider is obtained based on multi-tenancy strategy. See line 581 here. I don't see that happen in SchemaExport. Also if there are multiple data sources, SchemaExport should automatically create schema in other data sources as well. I don't see SchemaExport do anything like that.
See and JIRA issue . The JIRA issue does not have exact problem you described but there is work around suggested for creating schema in comments.
This is just my static analysis. You should probably open issue or wait here for someone to post answer. As far as I know, this seems to be bug or unsupported feature.
This is a bug in Hibernate...
https://hibernate.atlassian.net/browse/HHH-7395
As it is mentioned in blogs/books (e.g. Java Transactions Design Strategies by Mark Richards), read operations must have the Propagation.SUPPORTS attribute.
In a simple Spring 3.1 MVC project with Hibernate 4.1 the scenario is:
Declarative transaction management using #Transactional
sessionFactory of org.springframework.orm.hibernate4.LocalSessionFactoryBean
Transaction manager of org.springframework.orm.hibernate4.HibernateTransactionManager
Service class with #Transactional(propagation=Propagation.REQUIRED)
Function of that Service class that only retrieves a resultset (performs read operation) with #Transactional(propagation=Propagation.SUPPORTS)
Function of read operation retieves the resultset using sessionFactory.getCurrentSession().get()
Of course, when a Controller executes the function of read operation, the exception "No Session found for current thread" is raised because a transaction is not started and a session is not obtained.
Based on the above configuration (while it is best e.g. non-invasive, less code etc) the Propagation.SUPPORTS attribute cannot be used unless a transaction is started before with Propagation.REQUIRED or Propagation.REQUIRES_NEW.
How do we use use Propagation.SUPPORTS for read operations without having to start a transaction e.g. with Propagation.REQUIRED before but still taking advantage the benefits of declarative transaction management?
Thank you in advance.
Coder, here is the configuration:
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.myapps.service.impl" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driverClassName}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>.....</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
I disagree with using SUPPORTS for read operations. Use REQUIRED.
A transaction is needed anyway to perform every database operation
Doing several small transactions to read several things at once won't benefit from the first-level cache
There won't be any isolation between all the subsequent reads, meaning that something not visible to the first read might become visible for the second one
you'll get lazy loading exceptions when traversing associations
Transaction is not always required for Propagation.SUPPORTS.
Propagation.SUPPORTS: Support a current transaction, execute non-transactionally if none exists.
I have a complex situation where I have to use 2 different databases, there for I use 2 different transaction managers. Is there a way in Spring to link these transaction managers to work in a single transaction ? In case of an exception on the second dataSource changes on the first should be rolled-back.
<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#dummyHost:1521:dummySID" />
<property name="username" value="owner" />
<property name="password" value="password" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#dummyHost2:1521:dummySID2" />
<property name="username" value="owner" />
<property name="password" value="password" />
</bean>
<bean id="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource2" />
</bean>
You can use Spring's JtaTransactionManager to make sure both DBs are transacted with a single transaction manager.
Note, you would have to choose an underlying implementation which can either be a container's one: e.g. WebLogic, WebSphere and OC4J, etc.. or a stand alone, even an open source one: e.g. Atomikos.
HOWEVER
XA transaction management complicates things (configuration / performance / problem resolution / maintenance / etc.). And in a lot of cases, it can be avoided by clever patterns.
To get a solid understanding on whether you need to use XA ( e.g. distributed ) transaction manager, take a look at this fantastic article by Spring's own Dave Syer: Distributed transactions in Spring, with and without XA
You need a global transaction manager which supports 2-phase-commit (XA). Several independent and free ones are available. I've used Bitronix in a Spring-based project, but there is also Atomikos, and probably others. See http://en.wikipedia.org/wiki/Java_Transaction_API#Opensource_JTA_implementations
For routing through multiple datasource, You could use abstractRoutingDataSource but if you have requirements like one rollbackack affecting another you would need a JtaTransactionManager for distributed txn management .