We have an application which reads data from a database. We are using Spring JPA (OpenJPA implementation) to interact with the database. Currently We got an error if the database details is invalid. When an invalid database is configured, how can we handle the expection without crash our application.
Please find below the configuration class and the Persistance.xml file that we use. JPA MSSQL configuration class
@Configuration
@Profile("MSSQL")
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.sample",
entityManagerFactoryRef = "mssqlEntityManager", transactionManagerRef = "mssqlTransactionManager")
public class MSSqlContext
{
private static final String PACKAGES_TO_SCAN = "com.sample.mssql";
private static final String PERSISTANT_UNIT_NAME = "MssqlUnit";
@Resource
private Environment environment;
@Autowired
ApplicationContext appContext;
@Bean
public DataSource dataMssqlSource()
{
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("net.sourceforge.jtds.jdbc.Driver");
dataSource.setUrl("jdbc:jtds:sqlserver://127.0.0.1/DB");
dataSource.setUsername("test");
dataSource.setPassword("test");
return dataSource;
}
@Bean
public JpaTransactionManager mssqlTransactionManager() throws ClassNotFoundException
{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(this.mssqlEntityManager().getObject());
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean mssqlEntityManager() throws ClassNotFoundException
{
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(this.dataMssqlSource());
entityManagerFactoryBean.setPackagesToScan(PACKAGES_TO_SCAN);
entityManagerFactoryBean.setPersistenceProviderClass(PersistenceProviderImpl.class);
entityManagerFactoryBean.setPersistenceUnitName(PERSISTANT_UNIT_NAME);
entityManagerFactoryBean.afterPropertiesSet();
return entityManagerFactoryBean;
}
}
Persistance.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="IDSchemaPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>com.sample.entity.SampleEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="openjpa.Log" value="DefaultLevel=ERROR, Tool=ERROR" />
<property name="openjpa.jdbc.DBDictionary" value="mssql" />
<property name="openjpa.DataCache" value="true" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
</properties>
</persistence-unit>
</persistence>