How to integrate Spring with JDBC?

2019-09-16 15:51发布

问题:

I am currently using the following code to connect to a mysql database, but the project manager states I must make use of Spring framework to handle the connections.

How am I able to achive this?

And would the use of Spring to handle the database connections improve the quality of the overall system?

Here is an example of the class

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class SomeClass {
   Connection connection = null;
   ResultSet resultSet;
   Statement state;
   ArrayList aList = new ArrayList();

   public void connectToDatabase(String databaseName)
   {
      try
      {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         connection = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/" + databaseName, "username", "password");
         state = (Statement) connection.createStatement();
      }
      catch(Exception e)
      {
         JOptionPane.showMessageDialog(null, e);
      }
   }

private void populateAList() {
   try
   {
      connectToTable("testDB");
      resultSet = state.executeQuery("SELECT listItems FROM tblListItems WHERE ID = '" + theIDYouWant + "'");

      while(resultSet.next())
      {
         aList.add(resultSet.getString("listItems"));
      }

      resultSet.close();
      state.close();
   }
   catch(Exception e)
   {
      JOptionPane.showMessageDialog(null, e);
   }
}

}

回答1:

The Spring Reference Guide offers detailed documentation of its support for JDBC. At the bare minimum, using a JdbcTemplate--which requires nothing from you but new JdbcTemplate(...) for the most basic usage--would:

  • eliminate a lot of boilerplate code,
  • remove the ability to forget to close statements and connections,
  • lessen the temptation toward inappropriate exception handling, and
  • make it really easy to move away from inefficient connection handling.

The code you've shown suffers from all four of these, so I'd have to say that switching to Spring would be a huge benefit for you.

Also, if you're in a multithreaded app (all webapps are multithreaded), add "automatic thread-safety" to the list, which your code also lacks.