DbUnit H2 in memory db with Spring and Hibernate - spring

Hi I'm trying a little POC with JPA and unit test to verify that the DB schema is created. I'm working with H2 DB and I set to Hibernate create the schema from the entities, but when DbUnit tries to initialize the DB from a dataset I always get a Table ... not found in tableMap. I read that I have to add the property DB_CLOSE_DELAY=-1 to DB URL but is like after Hibernate creates the schema the DB is losted when DbUnit tries to initialize.
Any ideas? Any help is highly appreciated.
This is my config:
application-context.xml
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceH2" />
<property name="packagesToScan" value="com.xxx.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
<!-- property name="databasePlatform" value="org.hibernate.dialect.MySQLInnoDBDialect" /-->
<property name="databasePlatform" value="org.hibernate.dialect.H2Dialect" />
<!-- property name="database" value="MYSQL" /-->
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="javax.persistence.validation.mode">CALLBACK</prop>
</props>
</property>
</bean>
<bean id="dataSourceH2"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
RepositoryTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/application-context-test.xml" })
#Transactional
public class SystemEntityRepositoryH2Test {
#Inject
private SystemEntityRepository repository;
#Inject
private DataSource dataSourceH2;
private IDatabaseConnection connection;
#Before
public void setUp() throws Exception {
IDatabaseConnection dbUnitCon = null;
dbUnitCon = new DatabaseDataSourceConnection(dataSourceH2, "testdb");
dbUnitCon.getConfig().setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
IDataSet dataSet = this.getDataSet("dataset-systementity.xml");
DatabaseOperation.INSERT.execute(dbUnitCon, dataSet);
}
#After
public void tearDown() throws Exception {
//DatabaseOperation.DELETE_ALL.execute(this.getConnection(), this.getDataSet(dataSetFile));
}
#Test
public void test() throws Exception {
}
protected IDataSet getDataSet(String dataSetFile) throws Exception {
ResourceLoader resourceLoader = new ClassRelativeResourceLoader(this.getClass());
Resource resource = resourceLoader.getResource(dataSetFile);
if (resource.exists()) {
return new FlatXmlDataSetBuilder().build(resource.getInputStream());
}
return null;
}
}
dataset-systementity.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<System_Entities id="2" name="NAME" phone01="+52-55-55555555" email="a#a.com"
address01="Street" address02="123" address03="1" address04="Address04"
address05="Address05" city="City" state="State" country="MX"
zipcode="12345" />
</dataset>
Error
ERROR DatabaseDataSet:286 - Table 'System_Entities' not found in tableMap=org.dbunit.dataset.OrderedTableNameMap[_tableNames=[], _tableMap={}, _caseSensitiveTableNames=false]
I can see that the tables are created by hibernate because the log shows all the sql sentences without error.
Thanks.
SOLUTION
Thanks Mark Robinson
I modified the setUp method to:
#Before
public void setUp() throws Exception {
IDatabaseConnection dbUnitCon = null;
EntityManager entityManager = entityManagerFactory.createEntityManager();
Session session = entityManager.unwrap(Session.class);
SessionImplementor si = (SessionImplementor) session;
Connection conn = si.getJdbcConnectionAccess().obtainConnection();
dbUnitCon = new DatabaseConnection(conn);
//dbUnitCon.getConfig().setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
IDataSet dataSet = this.getDataSet("dataset-systementity.xml");
DatabaseOperation.INSERT.execute(dbUnitCon, dataSet);
}
It works now, what I don't understand yet is if I use HSQLDB I don't have this problem.

The problem is that DBUnit is loading the table data before Hibernate can initialize.
As part of your #setup, you'll need to get the Hibernate session. This should cause Hibernate to create your table. You could even force it by executing a simple query like select 1

Related

JdbcTemplate vs JPA query

I am facing strange problem where SAME query works via jdbctemplate.queryForList but does not work via JpaRepository #Query.
Both jdbctemplate and jpa entityManagerFactory+transactionManager use the same datasource, connecting to SQL Server.
When jpa query runs is returns: SQL Error: 942, SQLState: 42000; ORA-00942: table or view does not exist. Jdbctemplate query returns data from the db.
config xml:
<bean id="dataSourceSQL" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://host:1433;databaseName=SQLServerName"/>
<property name="username" value="***"/>
<property name="password" value="***"/>
</bean>
<bean id="jdbcTemplateSQL" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourceSQL" />
</bean>
<bean id="entityManagerFactorySQL" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSourceSQL">
</bean>
<bean id="transactionManagerSQL" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactorySQL" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerSQL" />
Repository.java
#Transactional(propagation=Propagation.MANDATORY, value="transactionManagerSQL")
public interface Repository extends JpaRepository<Users, Long>{
#Query(nativeQuery=true, value="select u.name from schema.Users u")
List<String> findUsers();
}
Test.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "classpath*:spring/config.xml" })
#TransactionConfiguration(transactionManager = "transactionManagerSQL", defaultRollback = true)
public class Test {
#Autowired Repository repository;
#Autowired JdbcTemplate jdbcTemplateSQL;
#Test
#Transactional("transactionManagerSQL")
public void testJpa() {
List<String> records = repository.findUsers(); //fails with table not found exception
assertNotNull(records);
}
#Test
public void testJdbcTemplate(){
List<Map<String, Object>> records=jdbcTemplateSQL.queryForList("select u.name from schema.Users u"); //returns results
assertNotNull(records);
}
}

Trying to persist to an oracle db using hibernate 4 and spring 3 without success. Tests pass but data not persisted.

I am trying to implement a simple DAO using hibernate 4 and Spring 3.
When I try to save or delete a row in the db the transaction is not persisted. I have included some code to show how the saving in the db doesnt work:
I have a junit test which simply tries to save a StockEntityDTO in the db.
#RunWith(SpringJUnit4ClassRunner.class)
public class StocksDAOImplTest extends
AbstractTransactionalJUnit4SpringContextTests {
#Autowired
protected StocksDAO stockDao;
#Test
public void shouldInsertIntoDatabase() {
BigDecimal price = new BigDecimal(653.50);
StockEntityDTO savedStock = new StockEntityDTO("GOOG", price, "google");
stockDao.create(savedStock);
StockEntityDTO retrievedStock = stockDao.getById(savedStock.getId());
assertEquals(savedStock, retrievedStock);
}
The test passes but the expected row (1, "GOOG", 653.50, "google") is not persisted in the db.
The DAO looks like this:
#Transactional
public abstract class AbstractHibernateDAO<T extends Serializable> {
private Class<T> clazz;
#Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
public void setClazz(final Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
public void create(final T entity) {
Session session = this.getCurrentSession();
session.save(entity);
}
Application Context:
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:orcl" />
<property name="username" value="gtp" />
<property name="password" value="gtp" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ubs.gtp.data.domain" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext
</prop>
</props>
</property>
</bean>
Hope someone can help. As is probably evident from my code, I am very new to spring.
AbstractTransactionalJUnit4SpringContextTests rolls back after the test. Try setting a breakpoint at the last line and then inspecting the database. You can use the Rollback annotation if you don't want this default behaviour.

Change SessionFactory datasource jdbcurl late in runtime

I'm writing a desktop java application for an environment without a network connection. I'm trying to store the application data as securely as I can in an encrypted in-process hsqldb, with an unencrypted user information hsqldb. Hsqldb requires that the crypto_key be set in the jdbcurl when the connection is created. My application uses hibernate to do persistence and Spring to do configuration and injection.
My current scheme is to store username, password hash, salt and the encrypted database's crypto_key in the unencrypted user table. The crypto_key is protected by an asymmetric encryption using the user's password as the key. Thus, the application doesn't know what the crypto_key for the application data is until after it has been running long enough to load a gui, and authenticate the user.
Here is my current applicationContext.xml. Spring uses it to get Hibernate going and functioning.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan base-package="com.company.domain" />
<context:component-scan base-package="com.company.service" />
<tx:annotation-driven />
<bean id="userDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url"
value="jdbc:hsqldb:./ReviewDatabase/users" />
<property name="username" value="reviewer" />
<property name="password" value="$kelatonKey" />
</bean>
<bean id="mainDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url"
value="jdbc:hsqldb:./ReviewDatabase/data" /> <!-- TODO: ;crypt_key=;crypt_type=AES -->
<property name="username" value="reviewer" />
<property name="password" value="$kelatonKey" />
</bean>
<bean id="userSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="userDataSource" />
<property name="annotatedClasses">
<list>
<value>com.company.domain.AppUser</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="mainSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="mainDataSource" />
<property name="annotatedClasses">
<list>
<!-- <value>com.companu.domain.Person</value> -->
<!-- <value>com.company.domain.Thing</value> -->
<!-- <value>com.company.domain.Thing1</value> -->
<!-- <value>com.company.domain.Thing2</value> -->
<!-- <value>com.company.domain.Review</value> -->
</list>
</property>
<property name="hibernateProperties">
<props>
<pro key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="mainTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mainSessionFactory" />
</bean>
<bean id="userTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="userSessionFactory" />
</bean>
</beans>
Here's an example of a class where I would like to have the SessionFactory injected
#Repository("ReviewDao")
public class HibernateReviewDao implements ReviewDao{
private SessionFactory mainSessionFactory;
#Autowired
public void setMainSessionFactory(
SessionFactory mainSessionFactory){
this.mainSessionFactory = mainSessionFactory;
}
#Override
#Transactional(value = "mainTransactionManager")
public void store(Review review) {
mainSessionFactory.getCurrentSession().saveOrUpdate(review);
}
#Override
#Transactional(value = "mainTransactionManager")
public void delete(Long reviewId) {
Review review = (Review)mainSessionFactory.getCurrentSession()
.get(Review.class, reviewId);
mainSessionFactory.getCurrentSession().delete(review);
}
}
And finally, here's what I've tried to do after authenticating the user and getting that crypto_key.
String jdbcUrl = "jdbc:hsqldb:./ReviewDatabase/data2;crypt_key=" + secret + ";crypt_type=AES";
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySetting("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
.applySetting("hibernate.show_sql", "true")
.applySetting("hibernate.hbm2ddl.auto","update")
.applySetting("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
.applySetting("hibernate.connection.url", jdbcUrl)
.applySetting("hibernate.connection.username", "reviewer")
.applySetting("hibernate.connection.password", "$kelatonKey")
.buildServiceRegistry();
SessionFactory mainSessionFactory = new MetadataSources(serviceRegistry)
.addAnnotatedClass(com.company.domain.Review.class)
.addAnnotatedClass(com.company.domain.Person.class)
.addAnnotatedClass(com.company.domain.Thing.class)
.addAnnotatedClass(com.company.domain.Thing1.class)
.addAnnotatedClass(com.company.domain.Thing2.class)
.buildMetadata()
.buildSessionFactory();
org.springframework.orm.hibernate4.HibernateTransactionManager htm =
(HibernateTransactionManager)context.getBean("mainTransactionManager");
context.getAutowireCapableBeanFactory().initializeBean(mainSessionFactory, "mainSessionFactory");
htm.setSessionFactory(mainSessionFactory);
However, with that, the first query to the object above results in org.hibernate.HibernateException: No Session found for current thread
How can I change the jdbcurl long after hibernate has initialized, dependencies have been injected and other various kinds of tom-foolery has occurred?
I've been putting this part of development off, hoping Google would eventually come through, but I'm out of ideas to search for. All answers will be accepted with sheepish humility :)
I wonder if this might help, Can I replace a Spring bean definition at runtime? , you could dummy up the bean properties to start with and then change the bean in runtime.
So, the missing bit of the recipe was LocalSessionFactoryBean. It got the sessionFactory setup so I could just replace the sessionFactories that are created at initialization.
Here's the code I had to change from the question
org.springframework.orm.hibernate4.HibernateTransactionManager htm =
(HibernateTransactionManager)context.getBean("mainTransactionManager");
Class<?>[] classes = new Class<?>[5];
classes[0] = com.company.domain.Thing1.class;
classes[1] = com.company.domain.Thing2.class;
classes[2] = com.company.domain.Person.class;
classes[3] = com.company.domain.Thing.class;
classes[4] = com.company.domain.Review.class;
String jdbcUrl = "jdbc:hsqldb:./ReviewDatabase/data3;crypt_key=" + secret + ";crypt_type=AES";
java.util.Properties hibernateProperties = new java.util.Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto","update");
hibernateProperties.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
hibernateProperties.setProperty("hibernate.connection.url", jdbcUrl);
hibernateProperties.setProperty("hibernate.connection.username", "reviewer");
hibernateProperties.setProperty("hibernate.connection.password", "$kelatonKey");
LocalSessionFactoryBean slfb = new LocalSessionFactoryBean();
slfb.setHibernateProperties(hibernateProperties);
slfb.setAnnotatedClasses(classes);
try {
slfb.afterPropertiesSet();
} catch (IOException e) {
Log.warn("Cannot connection to application database");
Log.write(e.getLocalizedMessage());
Log.write(e.getStackTrace());
return;
}
SessionFactory mainSessionFactory = slfb.getObject();
context.getAutowireCapableBeanFactory().initializeBean(mainSessionFactory, "mainSessionFactory");
htm.setSessionFactory(mainSessionFactory);
for(ListenForNewSessionFactory dao : daos){
dao.setNewSessionFactory(mainSessionFactory);
}
I had each Dao implement an interface to set the sessionFactory, and had each of them add themselves to a static list on initialization. It's not very reusable, but it works.
I used the following hack - wherever I needed a SessionFactory, I used a SessionFactoryFactory (below) instead - delegates the only SessionFactory method I actually use.
#Component
public class SessionFactoryFactory {
#Autowired
private LocalSessionFactoryBean sessionFactoryBean;
#Autowired
private DriverManagerDataSource dataSource;
private SessionFactory sessionFactory;
private SessionFactory getSessionFactory() {
if (null == sessionFactory) {
sessionFactory = sessionFactoryBean.getObject();
}
return sessionFactory;
}
public Session openSession() {
return getSessionFactory().openSession();
}
public void updateDataSourceUrl() throws IOException {
sessionFactory = null;
sessionFactoryBean.afterPropertiesSet();
}
}

Groovy and spring under same transaction

I'm struggling with legacy code. I'm creating unit tests so I've decided to use groovy to fill database with required legacy data. Normally in my code I using ibatis for persistence. I'd like to rollback test in the end. Problem is that when I create row via groovy then I use it's id to create row via ibatis I get constraint violation exception - parent key not found.
When I use groovy to persist parent and than create child based on parents id it works perfectly fine.
Also I can't use #Transactional because of problems with XML parser (legacy code FTW :/ )
#ContextConfiguration(locations = [ "../dao/impl/ibatis/spring-data-context-config.xml", "classpath:/pl/com/betacom/treq/dao-context.xml"])
#RunWith(SpringJUnit4ClassRunner.class)
public class FinancingForIltCreationTest {
#Autowired
IFinancingForIltDAO financingForIltDAO;
#Autowired
Sql sql;
#Autowired
DataSourceTransactionManager transactionManager;
private TransactionStatus transactionStatus;
#Before
public void setUp() {
transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
}
#After
public void tearDown() {
transactionManager.rollback(transactionStatus);
transactionStatus = null;
}
#Test
public void shallCreateFinancingForIlt() throws Exception {
//given
IltOffering offering = new IltOffering("GOING_DOWN_TO_UBERGROUND", offeringTempId, java.sql.Date.valueOf("2011-07-21"), java.sql.Date.valueOf("2012-07-21"));
offering.insert(sql); // it's inserted by groovy
//when
FinancingForIltDTO financingForIltDTO = createFinancingForIlt(offering.id).build(financingForIltDAO); // it's my assembler inserting via iBatis
//then
assertNotNull(financingForIltDTO.id);
}
Configuration looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dataSourceIn"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>####</value>
</property>
<property name="url">
<value>####</value>
</property>
<property name="username">
<value>####</value>
</property>
<property name="password">
<value>####</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg ref="dataSourceIn" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<bean id="sql" class="groovy.sql.Sql">
<constructor-arg ref="dataSource" />
</bean>
Unfortunately it was a database schema issue.

Datasource initialization at server start up

We have an application where we have used spring for IOC. We have the dataSource bean configured in applicationContext.xml and that is referenced in other bean definations.
The dataSource bean defination looks like:
<bean id="dbDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:oci:#TESTDB" />
<property name="username" value="TESTUSER" />
<property name="password" value="TESTPWD" />
<property name="initialSize" value="50" />
<property name="maxActive" value="40" />
<property name="maxIdle" value="10" />
<property name="minIdle" value="10" />
<property name="maxWait" value="-1" />
</bean>
<bean id="serviceDAO" class="com.test.impl.ServiceDAOImpl">
<property name="dataSource" ref="dbDataSource" />
</bean>
ServiceDAOImpl looks as follows:
public class ServiceDAOImpl implements ServiceDAO {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public ValueObj readValue(String key) {
String query = "SELECT * FROM SERVICE_LOOKUP WHERE KEY=?";
/**
* Implement the RowMapper callback interface
*/
return (ValueObj) jdbcTemplate.queryForObject(query,
new Object[] { key }, new RowMapper() {
public Object mapRow(ResultSet resultSet, int rowNum)
throws SQLException {
return new ValueObj(resultSet.getString("KEY"),
resultSet.getString("VALUE"));
}
});
}
public ServiceDAOImpl() {
}
}
Now, at the server start up injection is happening fine and when we use the dataSource in serviceDAOImpl the connection is happening fine. But the very first time the database call is made it takes around 3 mins to get the response back. I think this is because the pool creation is done during the first call and we have set the parameter "initialSize" = 50 in applicationConext.xml.
So, to avoid this we need a way in which the pool can be created during the application startup itself and can be used directly.
Please suggest. Let me know if any clarification required.
Regards
Saroj
There's a work-around for this .You could force jdbcTemplate to use the
DB connection at startup. See the link here for detailed explanation .
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg index="0" ref="dataSource"/>
<constructor-arg index="1" value="false"/>
</bean>
The second constructor-arg is the lazy Init flag.
Aravind A's solution is the preffered one, but just in case you don't want to define an extra bean you can point spring to your DAO's init method:
<bean id="serviceDAO" class="com.test.impl.ServiceDAOImpl" init-method="init">
<property name="dataSource" ref="dbDataSource" />
</bean>
and then define ServiceDAOImpl.init() which calls some sql like SELECT 1 FROM SERVICE_LOOKUP LIMIT 1 or even better some noop like SELECT 1:
public class ServiceDAOImpl implements ServiceDAO {
public void init() {
String query = "SELECT 1 FROM SERVICE_LOOKUP LIMIT 1";
int i = jdbcTemplate.queryForInt(query);
}
}

Resources