SimpleJDBCTemplate and AbstractDataSource configuration - spring

I am working on an app that uses SimpleJDBCTemplate as the wrapper to make JDBC calls.
However, instead of a conventional Datasource, I am choosing to use AbstractDataSource so I can choose from multiple data sources.
I am using ThreadLocal to inject keys to choose the appropriate Datasource.
However, it appears Spring is eagerly creating all my DAOs and my jdbcTemplate and hence I cannot figure out how to have the jdbcTemplate get Connection on demand.
Any clues.?

Do you mean AbstractRoutingDataSource? If not, you really should be using that, since this is exactly what it's for. Mark Fisher wrote a useful blog about it back when it was added to the framework.
Yes Spring will create your DAOs and JdbcTemplates eagerly if they're singletons, which is the default, but that doesn't mean they all obtain a connection immediately. A connection will only be obtained when you start some kind of operation that uses that data source. Typically, that would be starting a transaction. In other words, what you say you want to happen is what already happens.

Related

Is it a must to use spring-data-jdbc when using JdbcTemplate?

I am planning to use Spring JdbcTemplate to access my database. Is it a must to use spring-data-jdbc when using JdbcTemplate? The reason I am asking is I don't need "entity"(POJO) for my table in my application. Would it add some overheads if I use spring-data-jdbc?
You can use the JdbcTemplate without Spring Data JDBC without a problem.
JdbcTemplate existed for many years before Spring Data JDBC was conceived.
Spring Data JDBC does involve an overhead.
It extracts data from POJOs, creates queries and transforms the result back to POJOs.
Of course all that takes resources.
If you don't need/benefit from it don't use it.
You can also start with JdbcTemplate and later start using Spring Data JDBC without a problem if the need arises.
JdbcTemplate is part of the spring-jdbc module, so you only need that (and sprint-tx, which includes the DataAccessException hierarchy).
spring-data-jdbc adds support for (not surprisingly) spring-data on top of spring-jdbc. So you don't need it to use JdbcTemplate, the same as you don't need spring-data-jpa to use the JPA EntityManager.
Spring-data-jdbc is implemented on the basis of spring-jdbc. If you don't need Entity at all, then using spring-jdbc to interact directly with the database is the most convenient and flexible. In this case, using spring-data-jdbc is just a pure increase in learning costs. Spring-data-jdbc is designed for DDD (Domain Driven Design) mode, which is different from the current mainstream programming model. The learning cost is not low...

Spring JDBCTemplate and Hibernate

I have a Spring, Spring Data, JPA/Hibernate application.
The legacy part of the application uses JdbcTemplate the new stuff uses spring-data/hibernate and everything is wrapped in a transaction.
Problem is when I modify an entity via hibernate and the legacy part of the system attempts to query something that's been modified I don't get the updated values with out having to explicitly "flush" the entity manager each time.
Is it possible execute the JdbcTemplate queries against hibernate's first-level cache?
What about trying this?
Edit: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/jpa/JpaTransactionManager.html
This transaction manager also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access JPA and services which use plain JDBC (without being aware of JPA)! Application code needs to stick to the same simple Connection lookup pattern as with DataSourceTransactionManager (i.e. DataSourceUtils.getConnection(javax.sql.DataSource) or going through a TransactionAwareDataSourceProxy). Note that this requires a vendor-specific JpaDialect to be configured.

JMX in Spring: Is MBeanServerConnectionFactoryBean Thread-Safe

I have a spring based web-application that needs to get data from ActiveMQ via a JMX connection.
I am using MBeanServerConnectionFactoryBean (in Spring) to get various MBean attributes from ActiveMQ.
I have only one MBeanServerConnectionFactoryBean as a member variable, which is used to get the data. If multiple requests/threads come concurrently will there be any issues? Will there be any race conditions?
Please suggest the best way to keep the code thread-safe.
Spring FactoryBean objects are not intended to be used directly from your code, they're supposed to be used in your Spring config. As such, they are designed to be executed once and once only.
If you want to use them, including MBeanServerConnectionFactoryBean, then you need to create them, configure them, use them and discard them each and every time you want to get the object they create. They are most definitely not thread-safe.
Better yet, do it as the design intended and use them in your Spring config.

Is a singleton REST database resource a good idea?

Here's my situation. I have a class called somethingDao that contains all my logic for querying a table.
Then, I also have somethingDaoResource, which is a Jersey API resource, but also a Singleton, and is instantiating a somethingDao object via Spring (i.e., I'm injecting a datasource into somethingDao).
Then, I have a Jersey API businessLogicResource that does:
somethingDaoResource.getInstance().getsomethingDao() which gets me the somethingDao object at which I then fire multiple queries.
My question is, is this considered a good design? My main concern is that every time someone sends a HTTP request to my businessLogicResource, if the somethingDaoResource wasn't a Singleton (or a static?), then that would create a new instance of somethingDao, and open a new connection, which takes a while to do.
Any suggestions are more than welcome.
PS - I also have a c3p0 connection pool.
The most common practice is to have DAO objects as stateless singletons. Instead of opening and closing a connection they would borrow one from a pool and then return it when done. You can limit the maximum number of connections in the pool.
Having something statefull and a singleton in a web application is usually a bad idea. It might cause all kinds of read/write conflicts or thread locking. This approach also kills any possibility of distributing your application over a number of servers, which breaks one of the REST architectural constraints.

Is there a better way of detecting if a Spring DB transaction is active than using TransactionSynchronizationManager.isActualTransactionActive()?

I have some legacy code that I am now trying to re-use under Spring. This code is deeply nested in other code so it's not practical to redesign and is called in many situations, only some of which are through Spring. What I'd like to do is to use the Spring transaction if one has been started; otherwise, continue to use the existing (legacy) db connection mechanism. Our first thought was to make our legacy class a bean and use an injected TransactionPlatformManager, but that does not seem to have any methods germane to our situation. Some research showed that Spring has a class called TransactionSynchronizationManager which has a static method isActualTransactionActive(). My testing indicates this method is a reliable way of detecting if a Spring transaction is active:
When called via Spring service without the #Transactional annotation, it returns false
When called via Spring service with #Transactional, it returns true
In my legacy method called the existing way, it returns false
My question: Is there a better way of detecting if a transaction is active?
No better way than the TransactionSynchronizationManager.isActualTransactionActive(). It is the utility method used by spring to handle the transactions. Although it is not advisable to use it within your code, for some specific cases you should - that's why it's public.
Another way might be to use the entity manager / session / connection and check there if there's an existing transaction, but I'd prefer the synchronization manager.

Resources