Spring_基於Spring的JDBC

Spring的JDBC的有什麼用?

(打X表示要做的事)

使用了Spring的JDBC,我們只需要負責:配置數據庫連接參數,定義SQL(包含設置參數),處理結果集。

 

Spring的JDBC大大簡化了開發人員對數據庫的操作,使得開發人員可以從繁瑣的數據庫操作中解脫出來,

從而將更多的精力投入到編寫業務邏輯中。

 

Spring對ORM框架的支持

 

Spring的JDBC的使用

· 依賴的jar包

spring-jdbc,spring-tx,數據庫驅動包,連接池相關jar包(下文使用的是Driud連接池)。

 

· 配置數據庫連接參數

1、讓Spring管理DataSource對象

閱讀DruidDataSource類源代碼:

package com.alibaba.druid.pool;
public abstract class DruidAbstractDataSource extends WrapperAdapter implements 
DruidAbstractDataSourceMBean, DataSource, DataSourceProxy, Serializable {
    public void setUsername(String username) { /* 具體代碼略 */ }
    public void setPassword(String password) { /* 具體代碼略 */ }
    public void init() throws SQLException { /* 具體代碼略 */  }
    public void close() { /* 具體代碼略 */  }     
    // 其餘代碼略
}

可發現DruidDataSource提供了數據庫相關配置的屬性的setter方法,和init、close方法。

其中

則可以在Spring的xml配置文件中對屬性進行注入。

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql:///spring_demo" />
        <property name="username" value="root" />
        <property name="password" value="你的密碼" />
    </bean>

 

2、屬性佔位符的使用

上文,數據庫連接相關配置在Spring的配置文件中。而一般都會將數據庫的配置放置在properties文件中。

使用<context:property-placeholder>標籤可以方便我們,使用Spring讀取properties文件中的數據庫配置參數。

如下,在Spring的xml配置文件中配置:

<context:property-placeholder location="classpath:db.properties" />

其中location屬性爲數據庫配置文件的地址值(配合classpath前綴)

而後,DataSource的property中value屬性值就可以使用佔位符了。

配置效果如下

    <context:property-placeholder location="classpath:db.properties" />
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

數據庫配置文件: db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_study
jdbc.username=root
jdbc.password=你的密碼

(上文爲演示參數佔位符,所以在db.properties中的key加上了jdbc前綴)

 

· JdbcTemplate的使用

1、創建JdbcTemplate實例對象

閱讀源代碼,可發現創建JdbcTemplate對象需要一個DataSource對象。 

public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
    public JdbcTemplate(DataSource dataSource) {
        this.setDataSource(dataSource);
        this.afterPropertiesSet();
    }
}

在DAO實現類中,通過讓Spring注入DataSource屬性來創建JdbcTemplate對象。

@Repository
public class EmployeeDAOImpl implements IEmployeeDAO {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource ds){
        this.jdbcTemplate = new JdbcTemplate(ds);
    }

 

2、JdbcTemplate中常用的實例方法

update方法

用於增、刪、改操作。

query方法 

其RowMapper參數用於處理結果集。

實現其mapRow方法,操作每一行的結果集。如下例:

@Override
    public List<Employee> list() {
       List<Employee> list = this.jdbcTemplate.query("SELECT * FROM employee", 
            new RowMapper<Employee>() {
            @Override
            public Employee mapRow(ResultSet resultSet, int i) throws SQLException {
                Employee e = new Employee();
                e.setId(resultSet.getLong("id"));
                e.setName(resultSet.getString("name"));
                System.out.println(i);
                return e;
            }
        });
        return list;
    }

該方法也可以設置參數,如下例 :

@Override
    public Employee get(Long id) {
       List<Employee> list =  this.jdbcTemplate
            .query("SELECT * FROM employee WHERE id = ?", new RowMapper<Employee>() {
                    @Override
                    public Employee mapRow(ResultSet resultSet, int i) throws SQLException {
                        Employee e = new Employee();
                        e.setId(resultSet.getLong("id"));
                        e.setName(resultSet.getString("name"));
                        System.out.println(i);
                        return e;
                    }
                },id
        );
        return list.size() == 1 ? list.get(0) : null;
    }

 queryForObject方法

可以設置返回的類型。如下例:

@Override
    public Long getTotalCount() {
        Long totalCount = this.jdbcTemplate
                .queryForObject("SELECT COUNT(*) FROM employee", Long.class);
        return  totalCount;
    }

也可以處理結果集。返回的是單個對象。如下例:

@Override
    public Employee get(Long id) {
        Employee e =  this.jdbcTemplate.queryForObject("SELECT * FROM employee WHERE id = ?",
                new RowMapper<Employee>() {
          @Override
          public Employee mapRow(ResultSet resultSet, int i) throws SQLException {
              Employee e = new Employee();
              e.setId(resultSet.getLong("id"));
              e.setName(resultSet.getString("name"));
              System.out.println(i);
              return e;
          }
      }, id);
        return e;
    }

 

· JdbcDaoSupport

該類封裝了JdbcTemplate對象和DataSource的setter方法。

public abstract class JdbcDaoSupport extends DaoSupport {
    private JdbcTemplate jdbcTemplate;
    public JdbcDaoSupport() {
    }
    public final void setDataSource(DataSource dataSource) {
        if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
            this.jdbcTemplate = this.createJdbcTemplate(dataSource);
            this.initTemplateConfig();
        }
    }
    // 其餘代碼略
}

我們自定義的DAO實現類只要繼承JdbcDAOSupport類,

通過Spring的XML配置文件注入dataSource屬性,就可以通過super獲取到JdbcTemplate對象,

使用JdbcTemplate中的方法。

(若想使用註解方式,需將JdbcDaoSupport中的如上文所示的部分代碼,複製到自定義的DAO實現類中)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章