SpringBoot整合JDBCTemplate


一、spring JDBC

Spring框架對JDBC的簡單封裝。提供了一個JDBCTemplate對象簡化JDBC的開發。

步驟:

1、 添加依賴

2、創建JdbcTemplate對象。依賴於數據源DataSource

* JdbcTemplate template = new JdbcTemplate(ds);

3、調用JdbcTemplate的方法來完成CRUD的操作

* update():執行DML語句。增、刪、改語句。

* queryForMap():查詢結果將結果集封裝為map集合,將列名作為key,將值作為value 將這條記錄封裝為一個map集合。

  注意:這個方法查詢的結果集長度只能是1

* queryForList():查詢結果將結果集封裝為list集合。

  注意:將每一條記錄封裝為一個Map集合,再將Map集合裝載到List集合中

* query():查詢結果,將結果封裝為JavaBean對象。

  query的參數:RowMapper

  一般我們使用BeanPropertyRowMapper實現類。可以完成數據到JavaBean的自動封裝

  new BeanPropertyRowMapper<類型>(類型.class)

* queryForObject:查詢結果,將結果封裝為對象。

  一般用於聚合函數的查詢

二、Spring的JDBCTemplate入門

* 需求:
1)、修改1號數據的 salary 為 10000
2)、添加一條記錄
3)、刪除剛才添加的記錄
4)、查詢id為1的記錄,將其封裝為Map集合
5)、查詢所有記錄,將其封裝為List
6)、查詢所有記錄,將其封裝為Emp對象的List集合
7)、查詢總記錄數

1、創建maven的Java工程

補齊目錄后如下所示

2、添加依賴

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <!-- 連接到mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
    </dependencies>

3、在resources目錄下新建druid.properties文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcTemplate?useSSL=false&serverTimezone=UTC
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

4、創建emp表

CREATE TABLE `emp`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `ename` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `job_id` int(0) NULL DEFAULT NULL,
  `mgr` int(0) NULL DEFAULT NULL,
  `joindate` datetime(0) NULL DEFAULT NULL,
  `salary` double(10, 2) NULL DEFAULT NULL,
  `bonus` double(10, 2) NULL DEFAULT NULL,
  `dept_id` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

5、添加Druid連接池的工具類來獲取連接

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid連接池的工具類
 */
public class JDBCUtils {

    //1.定義成員變量 DataSource
    private static DataSource ds ;

    static{
        try {
            //1.加載配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.獲取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取連接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 釋放資源
     */
    public static void close(Statement stmt,Connection conn){
       /* if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();//歸還連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }*/

       close(null,stmt,conn);
    }


    public static void close(ResultSet rs , Statement stmt, Connection conn){


        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();//歸還連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 獲取連接池方法
     */

    public static DataSource getDataSource(){
        return  ds;
    }

}

測試能否獲取連接

public class DruidDemo {
    public static void main(String[] args) throws Exception {
        //1.導入jar包
        //2.定義配置文件
        //3.加載配置文件
        Properties pro = new Properties();
        InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        //4.獲取連接池對象
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        //5.獲取連接
        Connection conn = ds.getConnection();
        System.out.println(conn);

    }
}

結果如下:

com.mysql.cj.jdbc.ConnectionImpl@77caeb3e

6、創建實體類

@Data
@Accessors(chain = true)
public class Emp {
    private Integer id;
    private String ename;
    private Integer job_id;
    private Integer mgr;
    private Date joindate;
    private Double salary;
    private Double bonus;
    private Integer dept_id;

}

7、新建測試類進行測試

1)、添加

public class JdbcTemplateDemo2 {
    //1. 獲取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 1. 添加一條記錄
     */
    @Test
    public void test2(){
        String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
        int count = template.update(sql, 1015, "郭靖", 10);
        System.out.println(count);

    }
}

結果如下:

2)、修改

public class JdbcTemplateDemo2 {
    //1. 獲取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 1. 修改1015號數據的 salary 為 10000
     */
    @Test
    public void test1(){

        //2. 定義sql
        String sql = "update emp set salary = 10000 where id = 1015";
        //3. 執行sql
        int count = template.update(sql);
        System.out.println(count);
    }
}

結果如下:

3)、刪除

public class JdbcTemplateDemo2 {
    //1. 獲取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());/**
     * 3.刪除剛才添加的記錄
     */
    @Test
    public void test3(){
        String sql = "delete from emp where id = ?";
        int count = template.update(sql, 1015);
        System.out.println(count);
    }
}

4)、查詢

public class JdbcTemplateDemo2 {
    //1. 獲取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 4.查詢id為1001的記錄,將其封裝為Map集合
     * 注意:這個方法查詢的結果集長度只能是1
     */
    @Test
    public void test4(){
        String sql = "select * from emp where id = ?";
        Map<String, Object> map = template.queryForMap(sql, 1001);
        System.out.println(map);
        //{id=1001, ename=孫悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}

    }
}

結果如下:

{id=1001, ename=孫悟空, job_id=4, mgr=1004, joindate=2021-12-17 08:00:00.0, salary=10000.0, bonus=null, dept_id=20}

5)、查詢所有記錄,將其封裝成List

public class JdbcTemplateDemo2 {
    //1. 獲取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 5. 查詢所有記錄,將其封裝為List
     */
    @Test
    public void test5(){
        String sql = "select * from emp";
        List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
    }
}

結果:

{id=1001, ename=孫悟空, job_id=4, mgr=1004, joindate=2021-12-17 08:00:00.0, salary=10000.0, bonus=null, dept_id=20}
{id=1015, ename=郭靖, job_id=null, mgr=null, joindate=null, salary=10000.0, bonus=null, dept_id=10}

6)、查詢所有記錄,將其封裝為Emp對象的List集合

public class JdbcTemplateDemo2 {
    //1. 獲取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 6. 查詢所有記錄,將其封裝為Emp對象的List集合
     */
    @Test
    public void test6(){
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {

            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp = new Emp();
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");

                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                return emp;
            }
        });


        for (Emp emp : list) {
            System.out.println(emp);
        }
    }
}

結果如下:

Emp(id=1001, ename=孫悟空, job_id=4, mgr=1004, joindate=2021-12-17, salary=10000.0, bonus=0.0, dept_id=20)
Emp(id=1015, ename=郭靖, job_id=0, mgr=0, joindate=null, salary=10000.0, bonus=0.0, dept_id=10)

一般我們使用BeanPropertyRowMapper實現類。可以完成數據到JavaBean的自動封裝

public class JdbcTemplateDemo2 {
    //1. 獲取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Test
    public void test6_2(){
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }
}

三、SpringBoot整合JDBCTemplate

1、創建一個maven的java工程

2、添加依賴

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
        <!--測試的起步依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3、在resources目錄下添加application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/jdbcTemplate?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

4、創建emp表

CREATE TABLE `emp`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `ename` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `job_id` int(0) NULL DEFAULT NULL,
  `mgr` int(0) NULL DEFAULT NULL,
  `joindate` datetime(0) NULL DEFAULT NULL,
  `salary` double(10, 2) NULL DEFAULT NULL,
  `bonus` double(10, 2) NULL DEFAULT NULL,
  `dept_id` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

5、創建Emp類

@Data
@Accessors(chain = true)
public class Emp {
    private Integer id;
    private String ename;
    private Integer job_id;
    private Integer mgr;
    private Date joindate;
    private Double salary;
    private Double bonus;
    private Integer dept_id;

}

6、創建啟動類

@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class);
    }
}

7、創建啟動類進行測試

注意:JdbcTemplate直接注入即可

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class JdbcTemplateTest {
    @Resource
    private JdbcTemplate template;
    /**
     * 1. 添加一條記錄
     */
    @Test
    public void test2(){
        String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
        int count = template.update(sql, 1015, "郭靖", 10);
        System.out.println(count);

    }
    /**
     * 1. 修改1015號數據的 salary 為 10000
     */
    @Test
    public void test1(){

        //2. 定義sql
        String sql = "update emp set salary = 10000 where id = 1015";
        //3. 執行sql
        int count = template.update(sql);
        System.out.println(count);
    }

    /**
     * 3.刪除剛才添加的記錄
     */
    @Test
    public void test3(){
        String sql = "delete from emp where id = ?";
        int count = template.update(sql, 1015);
        System.out.println(count);
    }

    /**
     * 4.查詢id為1001的記錄,將其封裝為Map集合
     * 注意:這個方法查詢的結果集長度只能是1
     */
    @Test
    public void test4(){
        String sql = "select * from emp where id = ?";
        Map<String, Object> map = template.queryForMap(sql, 1001);
        System.out.println(map);
        //{id=1001, ename=孫悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}

    }

    /**
     * 5. 查詢所有記錄,將其封裝為List
     */
    @Test
    public void test5(){
        String sql = "select * from emp";
        List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
    }
    /**
     * 6. 查詢所有記錄,將其封裝為Emp對象的List集合
     */
    @Test
    public void test6(){
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {

            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp = new Emp();
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");

                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                return emp;
            }
        });


        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    @Test
    public void test6_2(){
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }
}

最后項目的目錄如下:

我們只需要在pom.xml中加入數據庫依賴,再到application.properties中配置連接信息,不需要像Spring應用中創建JdbcTemplate的Bean,就可以直接注入使用。

在test里做的測試,test包結構要保持與項目包結構一致,springboot才能自動掃描到包。


免責聲明!

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



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