Spring-JDBCTemplate


Spring 框架針對數據庫開發中的應用提供了 JDBCTemplate 類,該類是 Spring 對 JDBC 支持的核心,它提供了所有對數據庫操作功能的支持。

Spring 框架提供的JDBC支持主要由四個包組成,分別是 core(核心包)、object(對象包)、dataSource(數據源包)和 support(支持包),org.springframework.jdbc.core.JdbcTemplate 類就包含在核心包中。作為 Spring JDBC 的核心,JdbcTemplate 類中包含了所有數據庫操作的基本方法。

JdbcTemplate 類繼承自抽象類 JdbcAccessor,同時實現了 JdbcOperations 接口。其直接父類 JdbcAccessor 為子類提供了一些訪問數據庫時使用的公共屬性,具體介紹如下。

1)DataSource

其主要功能是獲取數據庫連接,具體實現時還可以引入對數據庫連接的緩沖池和分布式事務的支持,它可以作為訪問數據庫資源的標准接口。

2)SQLExceptionTranslator

org.springframework.jdbc.support.SQLExceptionTranslator 接口負責對 SQLException 進行轉譯工作。通過必要的設置或者獲取 SQLExceptionTranslator 中的方法,可以使 JdbcTemplate 在需要處理 SQLException 時,委托 SQLExceptionTranslator 的實現類完成相關的轉譯工作。

JdbcOperations 接口定義了在 JdbcTemplate 類中可以使用的操作集合,包括添加、修改、查詢和刪除等操作。

Spring 中 JDBC 的相關信息是在 Spring 配置文件中完成的,其配置模板如下所示:

<?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
http://www.springframework.org/schema/beans/spring-beans.xsd"> 

<!-- 配置數據源 --> 
<bean id="dataSource" class="org.springframework.jdbc.dataSource.DriverManagerDataSource">
<!--數據庫驅動-->
<property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
<!--連接數據庫的url-->
<property name= "url" value="jdbc:mysql://localhost/spring" />
<!--連接數據庫的用戶名-->
<property name="username" value="root" />
<!--連接數據庫的密碼-->
<property name="password" value="root" />
</bean>
<!--配置JDBC模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.jdbcTemplate">
<!--默認必須使用數據源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置注入類-->
<bean id="xxx" class="xxx">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
...
</beans>

 

在上述代碼中,定義了三個 Bean,分別是 dataSource、jdbcTemplate 和需要注入類的 Bean。其中 dataSource 對應的是 DriverManagerDataSource 類,用於對數據源進行配置;jdbcTemplate 對應 JdbcTemplate 類,該類中定義了 JdbcTemplate 的相關配置。

在 dataSource 中,定義了四個連接數據庫的屬性,如表 1 所示。

表 1 dataSource的四個屬性
屬性名 含義
driverClassName 所使用的驅動名稱,對應驅動 JAR 包中的 Driver 類
url 數據源所在地址
username 訪問數據庫的用戶名
password 訪問數據庫的密碼


表 1 中的屬性值需要根據數據庫類型或者機器配置的不同進行相應設置。如果數據庫類型不同,則需要更改驅動名稱。如果數據庫不在本地,則需要將 localhost 替換成相應的主機 IP。

在定義 jdbcTemplate 時,需要將 dataSource 注入 jdbcTemplate 中。而在其他的類中要使用 jdbcTemplate,也需要將 jdbcTemplate 注入使用類中(通常注入 dao 類中)。

在 JdbcTemplate 類中,提供了大量的查詢和更新數據庫的方法,如 query()、update() 等.

1.1.1 導入jar

 

 

 1.1.2Ctiy實體

public class City implements Serializable {
    private Integer cid;
    private String cname;
    private Integer pid;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }
}

Dao層

public interface AccountDao
{
    //匯款
    public void out(String outUser,Integer money);

    //收款
    public void in(String inUser,Integer money);

    //查詢方法
    public List<City> city();

    //刪除方法

    public Integer delect(Integer de);

    //增加方法

    public Integer add(City city);
}

Dao層實現類

@Repository
public class AccountDaoImpl  implements AccountDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    //匯款的實現方法
    @Override
    public void out(String outUser, Integer money) {
        this.jdbcTemplate.update("update city set pid=pid-? where cid=?",money,outUser);
    }
    //收款的實現方法
    @Override
    public void in(String inUser, Integer money) {
        this.jdbcTemplate.update("update city set pid=pid+? where cid=?",money,inUser);
    }

    RowMapper<City> rowMapper=new BeanPropertyRowMapper<>(City.class);
    @Override
    public List<City> city() {
        return jdbcTemplate.query("select * from city",rowMapper);
    }

    @Override
    public Integer delect(Integer de) {

        return jdbcTemplate.update("delete from city where cid=?",de);
    }
    @Override
    public Integer add(City city){
        String xml="insert INTO city(cid,cname,pid) values (?,?,?)";
        Object[] objects={city.getCid(),city.getCname(),city.getPid()};
        return jdbcTemplate.update(xml,objects);
    }
}

Service層

public interface AccountService {
    //轉賬
    public void transfet(String outUser,String inUser,Integer money);
    //查詢方法
    public List<City> city();

    //刪除方法

    public Integer delect(Integer de);

    //增加方法

    public Integer add(City city);
}

 

Service實現類

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }


    @Override
    public void transfet(String outUser, String inUser, Integer money) {
        this.accountDao.out(outUser,money);
        this.accountDao.in(inUser, money);
    }

    @Override
    public List<City> city() {
        return accountDao.city();
    }

    @Override
    public Integer delect(Integer de) {

        return accountDao.delect(de);
    }
    @Override
    public Integer add(City city) {

        return accountDao.add(city);
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--根節點是我們的beans節點-->
<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <!--掃描包-->
    <context:component-scan base-package="com.mengma"/>
    <!--加載properties文件-->
    <context:property-placeholder location="classpath:c3p0-db.properties"/>
    <!--配置數據源。讀取properties文件信息-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
        <property name="user" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />

    </bean>
    <!-- 配置dao -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

 

c3p0-db.properties

jdbc.driverClass =com.mysql.jdbc.Driver
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/test?serverTimezone=UTC 
jdbc.user = root
jdbc.password = root

 

測試

   @Test
    public void shouldAnswerWithTrue()
    {
        // 獲得Spring容器,並操作
        String xmlPath = "applicationContext.xml";
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        AccountService accountService = (AccountService) applicationContext.getBean("accountService");
        //修改操作
        accountService.transfet("130100", "130400", 100);
        //查詢操作
        List<City> cityList=accountService.city();
        for (City city:cityList){
            System.out.println(city.getCname());
        }
        //刪除操作
        accountService.delect(130000);
        //添加操作
        City city=new City();
        city.setCid(130000);
        city.setCname("超哥");
        city.setPid(12314);
        Integer add = accountService.add(city);

    }

以上代碼是實現注解方式

結構

 

 希望對你們有幫助,謝謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM