Best practices for Jdbc and configuring JdbcTemplate

Instances of the JdbcTemplate class are thread-safe once configured. As a best practice of configuring the JdbcTemplate in a Spring application, it should be constructed in the constructor injection or setter injection of the data source bean in your DAO classes by passing that data source bean as a constructor argument of the JdbcTemplate class. This leads to DAOs that look, in part, like the following:

    @Repository 
    public class JdbcAccountRepository implements AccountRepository{ 
      JdbcTemplate jdbcTemplate; 
    
      public JdbcAccountRepository(DataSource dataSource) { 
        super(); 
        this.jdbcTemplate = new JdbcTemplate(dataSource); 
      } 
      //... 
    } 
    Let's see some best practices to configure a database and write
the code for the DAO layer:
  • If you want to configure the embedded database at the time of development of the application, as the best practice, the embedded database will always be assigned a uniquely generated name. This is because in the Spring container, the embedded database is made available by configuring a bean of type javax.sql.DataSource, and that data source bean is injected to the data access objects.
  • Always use object pooling; this can be achieved in two ways:
    • Connection pooling: It allows the pool manager to keep the connections in a pool after they are closed
    • Statement pooling: It allows the driver to reuse the prepared Statement objects.
      • Choose the commit mode carefully
      • Consider removing the auto-commit mode for your application, and use manual commit instead to better control the commit logic, as follows:
                  Connection.setAutoCommit(false); 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset