Spring的JDBCTemplate

Spring的JdbcTemplate是對原始Jdbc API做的簡單封裝,簡化了我們對於數據庫的操作。
不過多的囉嗦了,直接上實例說明問題,我認爲就可以了,因爲這個內容並不複雜。
首先給出數據庫表的支持

create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('熊大',5000);
insert into account(name,money) values('熊二',5000);
insert into account(name,money) values('光頭強',1000);

導入本次實例所需的jar包

    <!--Spring jdbcTemplate所需的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <!--Spring開發包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!--用於數據庫的連接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <!--用於測試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

編寫實體類

/**
 * 賬戶實體類
 */
public class Account {

    private int id;
    private String name;
    private float money;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

編寫持久層接口及其實現類

/**
 * 持久層接口
 */
public interface AccountDao {

    /**
     *獲取所有賬戶信息
     * @return
     */
    List<Account> findAllAccount();

    /**
     *通過id獲取賬戶信息
     * @param id
     * @return
     */
    Account findAccountById(int id);

    /**
     * 保存賬戶
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新賬戶
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 通過id刪除賬戶信息
     * @param id
     */
    void deleteAccount(int id);

}
/**
 * 持久層接口實現類
 */
public class AccountDaoImpl implements AccountDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<Account> findAllAccount() {
        List<Account> accounts = jdbcTemplate.query("select *from account", new BeanPropertyRowMapper<Account>(Account.class));
        return accounts;
    }

    public Account findAccountById(int id) {
        Account account = jdbcTemplate.queryForObject("select *from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
        return account;
    }

    public void saveAccount(Account account) {
        jdbcTemplate.update("insert into account(name,money)values (?,?)",account.getName(),account.getMoney());
    }

    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set name=?, money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }

    public void deleteAccount(int id) {
        jdbcTemplate.update("delete from account where id = ?",id);
    }
}

編寫XML配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置持久層實現類-->
    <bean id="accountDao" class="com.liang.dao.impl.AccountDaoImpl">
        <!--注入數據庫操作模版-->
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!--配置數據庫操作模版-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置數據源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="liang"></property>
    </bean>
</beans>

編寫測試類

public class JDbcTemplate {

    private AccountDao accountDao;
    @Before
    public void init()
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        accountDao = (AccountDao)applicationContext.getBean("accountDao");
    }

    @Test
    public void testFindAllAccount()
    {
        List<Account> accounts = accountDao.findAllAccount();
        for (Account account:accounts)
        {
            System.out.println(account);
        }
    }

    @Test
    public void testFindAccountById()
    {
        Account account = accountDao.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSaveAccount()
    {
        Account account = new Account();
        account.setName("小花貓");
        account.setMoney(100f);
        accountDao.saveAccount(account);
    }

    @Test
    public void testUpdateAccount()
    {
        Account account = accountDao.findAccountById(4);
        account.setMoney(10.0f);
        accountDao.updateAccount(account);
    }

    @Test
    public void testDeleteAccount()
    {
        accountDao.deleteAccount(4);
    }
}

按照以上的方法,如果有多個持久層接口實現類的時候,便會發現有段代碼的重複性很高。
在這裏插入圖片描述
其中Spring框架爲我們提供瞭解決辦法:Spring中有一個JdbcDaoSupport類,該類中定義了一個JdbcTemplate對象,可以幫助我們解決上面的重複性問題,該類在創建JdbcTemplate對象時候,需要提供一個數據源。
修改持久層實現類

/**
 * 持久層接口實現類
 */
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {


    public List<Account> findAllAccount() {
        List<Account> accounts = super.getJdbcTemplate().query("select *from account", new BeanPropertyRowMapper<Account>(Account.class));
        return accounts;
    }

    public Account findAccountById(int id) {
        Account account = super.getJdbcTemplate().queryForObject("select *from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
        return account;
    }

    public void saveAccount(Account account) {
        super.getJdbcTemplate().update("insert into account(name,money)values (?,?)",account.getName(),account.getMoney());
    }

    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?, money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }

    public void deleteAccount(int id) {
        super.getJdbcTemplate().update("delete from account where id = ?",id);
    }
}

修改XML配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置持久層實現類-->
    <bean id="accountDao" class="com.liang.dao.impl.AccountDaoImpl">
        <!--注入數據源-->
       <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <!--配置數據源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/itcast?serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="liang"></property>
    </bean>
</beans>
發佈了71 篇原創文章 · 獲贊 6 · 訪問量 5380
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章