Spring 系列之jdbcTemplate的使用


Spring系列之 jdbcTemplate

在這里插入圖片描述

啥是jdncTemplate?

t他是spring框架中提供的一個對象,是對原始的jdbcAPI對象的簡單封裝,spring框架為我們提供了很多操作,模板類,比如操作關系型數據庫的jdbcTemplate,操作nosql數據庫的Redis Template,操作消息隊列的jmsTemplate等等

JdbcTemplate開發步驟

1.導入sprign-jdbc和spring-tx坐標
2.創建數據庫表和實體
3.創建JdbcTemplate對象
4.執行數據庫操作

1.導入sprign-jdbc和spring-tx坐標

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.0.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.0.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.32</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.9</version>
    </dependency>
</dependencies>

2.創建數據庫表和實體

使用sqlyog創建一個表
語句

CREATE TABLE test1(
id INT,
NAME VARCHAR(10)
 );

創建實體

package com.pjh;
public class user {
    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "user{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

JbdcTemplate快速入門*,不使用spring框架的時候

@Test
    public void test1() throws PropertyVetoException {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
    comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3309/one");
    comboPooledDataSource.setUser("root");
    comboPooledDataSource.setPassword("1234");
    //創建jdbcTemplate對象
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(comboPooledDataSource);
    //執行語句
    jdbcTemplate.update("insert into test1 values(?,?)",10,"one");
}

結果

在這里插入圖片描述
抽取配置文件

配置文件代碼:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3309/one
jdbc.name=root
jdbc.password=1234

測試函數操作

@Test
public void test3() throws PropertyVetoException {
    //讀取配置文件
    ResourceBundle jdbc = ResourceBundle.getBundle("jdbc");
    //獲取連接池
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    //設置參數
    comboPooledDataSource.setDriverClass(jdbc.getString("jdbc.driver"));
    comboPooledDataSource.setJdbcUrl(jdbc.getString("jdbc.url"));
    comboPooledDataSource.setUser(jdbc.getString("jdbc.name"));
    comboPooledDataSource.setPassword(jdbc.getString("jdbc.password"));
    //創建jdbcTemplate對象
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(comboPooledDataSource);
    jdbcTemplate.update("insert into test1 values(?,?)",13,"three");

}

使用spring創建JdbcTemplate對象
將數據源DataSource與JdbcTemplate的創建權交給Spring並在Spring容器內進行依賴注入
配置代碼:


<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3309/one"/>
    <property name="user" value="root"/>
    <property name="password" value="1234"/>
</bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="datasource"/>
    </bean>

測試函數

@Test
    public void test2(){
    ClassPathXmlApplicationContext classPathXmlApplicationContext =
            new ClassPathXmlApplicationContext("applicationContext.xml");
    JdbcTemplate jdbcTemplate =(JdbcTemplate) classPathXmlApplicationContext.getBean("jdbcTemplate");
    jdbcTemplate.update("insert into test1 values(?,?)",11,"two");
}

結果
成功插入
在這里插入圖片描述

這個也可以使用讀取配置文件的方式
我們首先要導入context的約束路徑與命名空間

命名空間: xmlns:context="http://www.springframework.org/schema/context"
約束路徑:http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

配置文件修改

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
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="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.name}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="datasource"/>
    </bean>
   <context:property-placeholder location="classpath:jdbc.properties"/>
</beans>

測試代碼

 @Test
    public void test4(){
        ClassPathXmlApplicationContext classPathXmlApplicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate =(JdbcTemplate) classPathXmlApplicationContext.getBean("jdbcTemplate");
        jdbcTemplate.update("insert into test1 values(?,?)",100,"pjh");
    }

結果
成功插入
在這里插入圖片描述

通過注解的方式來得到JdbcTemplate
使用框架

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Autowired
private  JdbcTemplate jdbcTemplate;
    @Test
    public void test7(){
        jdbcTemplate.update("insert into test1 values(?,?)",110,"GGB");

    }

不使用框架

public void test1() throws PropertyVetoException {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
    comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3309/one");
    comboPooledDataSource.setUser("root");
    comboPooledDataSource.setPassword("1234");
    //創建jdbcTemplate對象
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(comboPooledDataSource);
    //執行語句
    jdbcTemplate.update("insert into test1 values(?,?)",10,"one");
}

由二者對比即可看出框架的巨大好處,上面那么長的代碼現在只要幾行即可解決

在這里插入圖片描述

JDBCTemplate的常用操作

查詢語句

查詢數據庫中的所有內容

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Autowired
private  JdbcTemplate jdbcTemplate;
   @Test
public void test8(){
    String sql="select * from test1 where name=?";
    List<user> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<user>(user.class));
    for (user user : query) {
        System.out.println(user);
    }
}

結果

在這里插入圖片描述

查詢數據庫中的某條內容

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Autowired
private  JdbcTemplate jdbcTemplate;
   @Test
 @Test
    public void test9(){
        String sql="select * from test1 where id=?";
        List<user> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<user>(user.class), 10);
        for (user user : query) {
            System.out.println(user);
        }
    }
}

查詢數據庫記錄的數量

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Autowired
private  JdbcTemplate jdbcTemplate;
@Test
public void test90(){
    String sql="select count(*) from test1";
    Long aLong = jdbcTemplate.queryForObject(sql, Long.class);
    System.out.println("記錄條數:"+aLong);
}
}

刪除指定記錄

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Autowired
private  JdbcTemplate jdbcTemplate;
@Test
public void test11(){
    String sql="delete from test1 where id=11";
    jdbcTemplate.update(sql);
}
}

以上就是Spring jdbc操作的一些知識,我會不斷的學習,也會不斷更新我的學習文章,主要有java和數據結構兩個方面,有想要一起學習的伙伴可以私信或則關注我,共勉

在這里插入圖片描述


免責聲明!

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



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