上一篇Spring博文主要講解了如何使用Spring來實現AOP編程,本博文主要講解Spring的對JDBC的支持…javascript
對於JDBC而言,咱們確定不會陌生,咱們在初學的時候確定寫過很是很是多的JDBC模板代碼!java
咱們來回憶一下咱們怎麼對模板代碼進行優化的!mysql
try { String sql = "insert into t_dept(deptName) values('test');"; Connection con = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); // 鏈接對象 con = DriverManager.getConnection("jdbc:mysql:///hib_demo", "root", "root"); // 執行命令對象 stmt = con.createStatement(); // 執行 stmt.execute(sql); // 關閉 stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); }
/* * 鏈接數據庫的driver,url,username,password經過配置文件來配置,能夠增長靈活性 * 當咱們須要切換數據庫的時候,只須要在配置文件中改以上的信息便可 * * */ private static String driver = null; private static String url = null; private static String username = null; private static String password = null; static { try { //獲取配置文件的讀入流 InputStream inputStream = UtilsDemo.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(inputStream); //獲取配置文件的信息 driver = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); //加載驅動類 Class.forName(driver); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,username,password); } public static void release(Connection connection, Statement statement, ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
上面已經回顧了一下之前咱們的JDBC開發了,那麼看看Spring對JDBC又是怎麼優化的spring
首先,想要使用Spring的JDBC模塊,就必須引入兩個jar文件:sql
引入jar文件數據庫
首先仍是看一下咱們原生的JDBC代碼:獲取Connection是能夠抽取出來的,直接使用dataSource來獲得Connection就好了。編程
public void save() { try { String sql = "insert into t_dept(deptName) values('test');"; Connection con = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); // 鏈接對象 con = DriverManager.getConnection("jdbc:mysql:///hib_demo", "root", "root"); // 執行命令對象 stmt = con.createStatement(); // 執行 stmt.execute(sql); // 關閉 stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } }
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="10"></property> <property name="maxStatements" value="100"></property> <property name="acquireIncrement" value="2"></property> </bean>
// IOC容器注入 private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void save() { try { String sql = "insert into t_dept(deptName) values('test');"; Connection con = null; Statement stmt = null; // 鏈接對象 con = dataSource.getConnection(); // 執行命令對象 stmt = con.createStatement(); // 執行 stmt.execute(sql); // 關閉 stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } }
Spring來提供了JdbcTemplate這麼一個類給咱們使用!它封裝了DataSource,也就是說咱們能夠在Dao中使用JdbcTemplate就好了。markdown
建立dataSource,建立jdbcTemplate對象app
<?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:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql:///zhongfucheng"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="10"></property> <property name="maxStatements" value="100"></property> <property name="acquireIncrement" value="2"></property> </bean> <!--掃描註解--> <context:component-scan base-package="bb"/> <!-- 2. 建立JdbcTemplate對象 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
package bb; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; /** * Created by ozc on 2017/5/10. */ @Component public class UserDao implements IUser { //使用Spring的自動裝配 @Autowired private JdbcTemplate template; @Override public void save() { String sql = "insert into user(name,password) values('zhoggucheng','123')"; template.update(sql); } }
@Test public void test33() { ApplicationContext ac = new ClassPathXmlApplicationContext("bb/bean.xml"); UserDao userDao = (UserDao) ac.getBean("userDao"); userDao.save(); }
咱們要是使用JdbcTemplate查詢會發現有不少重載了query()方法ide
通常地,若是咱們使用queryForMap(),那麼只能封裝一行的數據,若是封裝多行的數據、那麼就會報錯!而且,Spring是不知道咱們想把一行數據封裝成是什麼樣的,所以返回值是Map集合…咱們獲得Map集合的話還須要咱們本身去轉換成本身須要的類型。
咱們通常使用下面這個方法:
咱們能夠實現RowMapper,告訴Spriing咱們將每行記錄封裝成怎麼樣的。
public void query(String id) { String sql = "select * from USER where password=?"; List<User> query = template.query(sql, new RowMapper<User>() { //將每行記錄封裝成User對象 @Override public User mapRow(ResultSet resultSet, int i) throws SQLException { User user = new User(); user.setName(resultSet.getString("name")); user.setPassword(resultSet.getString("password")); return user; } },id); System.out.println(query); }
固然了,通常咱們都是將每行記錄封裝成一個JavaBean對象的,所以直接實現RowMapper,在使用的時候建立就行了。
class MyResult implements RowMapper<Dept>{ // 如何封裝一行記錄 @Override public Dept mapRow(ResultSet rs, int index) throws SQLException { Dept dept = new Dept(); dept.setDeptId(rs.getInt("deptId")); dept.setDeptName(rs.getString("deptName")); return dept; } }