This is the third part of Spring Best Practices series as per Best practices introduction post. This third part is related with the best practices when using Spring’s DAO layers. You can refer the other four posts through this links… Part 1, Part 2, Part 4 and Part 5. I am expecting the corrections (if any)as well as the new best ways from my readers.
- Prefer to use apache Connection pooling bean
In the spring DataSource Configuration we are commonly using class is “org.springframework.jdbc.datasource.DriverManagerDataSource”. We can implement connection pooling using the following class “org.apache.commons.dbcp.BasicDataSource”. For that we have to download its jar file from apache commons.Project site: http://commons.apache.org/dbcp/Download: http://commons.apache.org/downloads/download_dbcp.cgi
- Handling Exceptions
Spring Gives a consistent exception hierarchy in its DAO level. All the SQL as well as DAO based exceptions are under the DataAccessException. With the effective handling of this exception, we can easily log the errors as well as we can more effectively assign “ERROR MESSAGES” to the error objects.We can also use Spring’s “org.springframework.web.servlet.handler.SimpleMappingExceptionResolver” class to get the exceptions thrown and can be displayed in the web level. This will help us to check the “Exceptions in a real distributed environment”.
- Prefer to use Springs Declarative Transaction Capability
Spring provides Programmatic as well as Declarative Transaction capabilities. And if we are using any OR mapping tools then spring provides its own Transaction manager to handle it.
- Transaction Attribute Settings.
Spring provides a distinct “ISOLATION behaviors” for handling transactions. In which the most efficient isolation level, but isolates the transaction the least, leaving the transaction open to dirty, no repeatable, and phantom reads. At the other extreme, ISOLATION_SERIALIZABLE prevents all forms of isolation problems but least efficient. So its better to choose according to our needs.
- Better to perform unit testing in the DAO layer.
The Data Access Part is the important part in which errors are popping up. So if we complete a unit test here then it will be more useful for our service layer programming. It’s very easy to write unit tests in the spring DAO layers. Junit (http://www.junit.org/ ), easymock(http://www.easymock.org/ ), unitils (http://unitils.sourceforge.net/summary.html ) are some of the useful as well as mostly used Unit testing frameworks. Each one has its own advantages.