spring中的JdbcTemplate如何使用?

前言

JdbcTemplate前世今生,很久很久以前,當我們剛剛要踏入程序猿的行列,還是一隻菜鳥的時候,我們天真的以爲踏踏實實才是真。所以,我們堅守着最初的誓言,每次在做持久層技術選型的時候,我們總是選擇最原始的JDBC,快樂的coding。

直到有一天,Java界的武林盟主-Spring,爲了進一步鞏固自己在Java開發領域的地位,無情的搶走了它,隨即對它做了一系列的封裝改造,從此我們再也見不到它了,但是總能依稀感覺到它的存在,從此就誕生了JdbcTemplate,這就是JdbcTemplate的由來。

spring中的JdbcTemplate如何使用?

Spring官方有一句非常經典的宣言"Don't Reinvent theWheel",翻譯過來就是"不要重複發明輪子"。

所以我們可以看到很多Spring出品的技術都是在原有的技術基礎之上進一步封裝、重構、改造,也因此成就了Spring這樣一個偉大的技術生態,在Java開發領域做出了非常大的貢獻。JdbcTemplate的存在無疑也是最好的見證。

Tips:凡是我們看到xxxTemplate的類,都是Spring對xxx的封裝的模板類。

什麼是JdbcTemplate

我們都知道使用原始的JDBC在操作數據庫是比較麻煩的,所以Spring爲了提高開發的效率,順帶着就把JDBC封裝、改造了一番,而JdbcTemplate就是Spring對原始JDBC封裝之後提供的一個操作數據庫的工具類。

我們可以藉助JdbcTemplate來完成所有數據庫操作,比如:增刪改查等。改造之後的JdbcTemplate主要提供以下三種類型的方法

  1. executeXxx() : 執行任何SQL語句,對數據庫、表進行新建、修改、刪除操作
  2. updateXxx() : 執行新增、修改、刪除等語句
  3. queryXxx() : 執行查詢相關的語句

JdbcTemplate配置連接池

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

  1. public JdbcTemplate(DataSource dataSource)
    創建JdbcTemplate對象,方便執行SQL語句
  2. public void execute(final String sql)
    execute可以執行所有SQL語句,因爲沒有返回值,一般用於執行DDL語句。

JdbcTemplate使用步驟

  1. 準備DruidDataSource連接池
  2. 導入依賴的jar包
    • spring-beans-4.1.2.RELEASE.jar
    • spring-core-4.1.2.RELEASE.jar
    • spring-jdbc-4.1.2.RELEASE.jar
    • spring-tx-4.1.2.RELEASE.jar
    • com.springsource.org.apache.commons.logging-1.1.1.jar
  3. 創建JdbcTemplate對象,傳入Druid連接池
  4. 調用executeupdatequeryXxx等方法

案例代碼

public class Demo04 {
    public static void main(String[] args) {
        // 創建表的SQL語句
        String sql = "CREATE TABLE product("
                + "pid INT PRIMARY KEY AUTO_INCREMENT,"
                + "pname VARCHAR(20),"
                + "price DOUBLE"
                + ");";

        JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
        jdbcTemplate.execute(sql);
    }
}

JdbcTemplate實現增刪改

API介紹

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

  1. public int update(final String sql)
    用於執行`INSERT`、`UPDATE`、`DELETE`等DML語句。

使用步驟

1.創建JdbcTemplate對象
2.編寫SQL語句
3.使用JdbcTemplate對象的update方法進行增刪改

案例代碼

public class Demo05 {
    public static void main(String[] args) throws Exception {
//      test01();
//      test02();
//      test03();
    }

    // JDBCTemplate添加數據
    public static void test01() throws Exception {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());

        String sql = "INSERT INTO product VALUES (NULL, ?, ?);";

        jdbcTemplate.update(sql, "iPhone3GS", 3333);
        jdbcTemplate.update(sql, "iPhone4", 5000);
        jdbcTemplate.update(sql, "iPhone4S", 5001);
        jdbcTemplate.update(sql, "iPhone5", 5555);
        jdbcTemplate.update(sql, "iPhone5C", 3888);
        jdbcTemplate.update(sql, "iPhone5S", 5666);
        jdbcTemplate.update(sql, "iPhone6", 6666);
        jdbcTemplate.update(sql, "iPhone6S", 7000);
        jdbcTemplate.update(sql, "iPhone6SP", 7777);
        jdbcTemplate.update(sql, "iPhoneX", 8888);
    }

    // JDBCTemplate修改數據
    public static void test02() throws Exception {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());

        String sql = "UPDATE product SET pname=?, price=? WHERE pid=?;";

        int i = jdbcTemplate.update(sql, "XVIII", 18888, 10);
        System.out.println("影響的行數: " + i);
    }

    // JDBCTemplate刪除數據
    public static void test03() throws Exception {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
        String sql = "DELETE FROM product WHERE pid=?;";
        int i = jdbcTemplate.update(sql, 7);
        System.out.println("影響的行數: " + i);
    }
}

JdbcTemplate查詢-queryForInt返回一個int整數

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

API介紹

public int queryForInt(String sql)
執行查詢語句,返回一個int類型的值。

使用步驟

  1. 創建JdbcTemplate對象
  2. 編寫查詢的SQL語句
  3. 使用JdbcTemplate對象的queryForInt方法
  4. 輸出結果

案例代碼

// queryForInt返回一個整數
public static void test01() throws Exception {
   // String sql = "SELECT COUNT(*) FROM product;";
   String sql = "SELECT pid FROM product WHERE price=18888;";
   JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
   int forInt = jdbcTemplate.queryForInt(sql);
   System.out.println(forInt);
}

JdbcTemplate查詢-queryForLong返回一個long整數

講解

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

API介紹

public long queryForLong(String sql)
執行查詢語句,返回一個long類型的數據。

使用步驟

  1. 創建JdbcTemplate對象
  2. 編寫查詢的SQL語句
  3. 使用JdbcTemplate對象的queryForLong方法
  4. 輸出結果

案例代碼

// queryForLong  返回一個long類型整數
public static void test02() throws Exception {
   String sql = "SELECT COUNT(*) FROM product;";
   // String sql = "SELECT pid FROM product WHERE price=18888;";
   JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
   long forLong = jdbcTemplate.queryForLong(sql);
   System.out.println(forLong);
}

JdbcTemplate查詢-queryForObject返回String

講解

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

API介紹

public <T> T queryForObject(String sql, Class<T> requiredType)
執行查詢語句,返回一個指定類型的數據。

使用步驟

  1. 創建JdbcTemplate對象
  2. 編寫查詢的SQL語句
  3. 使用JdbcTemplate對象的queryForObject方法,並傳入需要返回的數據的類型
  4. 輸出結果

案例代碼

public static void test03() throws Exception {
   String sql = "SELECT pname FROM product WHERE price=7777;";
   JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
   String str = jdbcTemplate.queryForObject(sql, String.class);
   System.out.println(str);
}

JdbcTemplate查詢-queryForMap返回一個Map集合

API介紹

public Map<String, Object> queryForMap(String sql)
執行查詢語句,將一條記錄放到一個Map中。

使用步驟

  1. 創建JdbcTemplate對象
  2. 編寫查詢的SQL語句
  3. 使用JdbcTemplate對象的queryForMap方法
  4. 處理結果
public static void test04() throws Exception {
   String sql = "SELECT * FROM product WHERE pid=?;";
   JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
   Map<String, Object> map = jdbcTemplate.queryForMap(sql, 6);
   System.out.println(map);
}

JdbcTemplate查詢-queryForList返回一個List集合

目標

能夠掌握JdbcTemplate中queryForList方法的使用

講解

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

API介紹

public List<Map<String, Object>> queryForList(String sql)
執行查詢語句,返回一個List集合,List中存放的是Map類型的數據。

使用步驟

  1. 創建JdbcTemplate對象
  2. 編寫查詢的SQL語句
  3. 使用JdbcTemplate對象的queryForList方法
  4. 處理結果
public static void test05() throws Exception {
   String sql = "SELECT * FROM product WHERE pid<?;";
   JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
   List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 8);
   for (Map<String, Object> map : list) {
      System.out.println(map);
   }
}

queryForList方法的作用?將返回的一條記錄保存在Map集合中,多條記錄對應多個Map,多個Map存儲到List集合中

JdbcTemplate查詢-RowMapper返回自定義對象

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

API介紹

public <T> List<T> query(String sql, RowMapper<T> rowMapper)
執行查詢語句,返回一個List集合,List中存放的是RowMapper指定類型的數據。

使用步驟

  1. 定義Product類
  2. 創建JdbcTemplate對象
  3. 編寫查詢的SQL語句
  4. 使用JdbcTemplate對象的query方法,並傳入RowMapper匿名內部類
  5. 在匿名內部類中將結果集中的一行記錄轉成一個Product對象

案例代碼

// query使用rowMap做映射返回一個對象
public static void test06() throws Exception {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());

   // 查詢數據的SQL語句
   String sql = "SELECT * FROM product;";

   List<Product> query = jdbcTemplate.query(sql, new RowMapper<Product>() {
      @Override
      public Product mapRow(ResultSet arg0, int arg1) throws SQLException {
         Product p = new Product();
         p.setPid(arg0.getInt("pid"));
         p.setPname(arg0.getString("pname"));
         p.setPrice(arg0.getDouble("price"));
         return p;
      }
   });

   for (Product product : query) {
      System.out.println(product);
   }
}
  1. 使用JdbcTemplate對象的query方法,並傳入RowMapper匿名內部類
  2. 在匿名內部類中將結果集中的一行記錄轉成一個Product對象

JdbcTemplate查詢-BeanPropertyRowMapper返回自定義對象

org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句

API介紹

public <T> List<T> query(String sql, RowMapper<T> rowMapper)
執行查詢語句,返回一個List集合,List中存放的是RowMapper指定類型的數據。
public class BeanPropertyRowMapper<T> implements RowMapper<T>
BeanPropertyRowMapper類實現了RowMapper接口

使用步驟

  1. 定義Product類
  2. 創建JdbcTemplate對象
  3. 編寫查詢的SQL語句
  4. 使用JdbcTemplate對象的query方法,並傳入BeanPropertyRowMapper對象
// query使用BeanPropertyRowMapper做映射返回對象
public static void test07() throws Exception {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());

    // 查詢數據的SQL語句
    String sql = "SELECT * FROM product;";
    List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));

    for (Product product : list) {
        System.out.println(product);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章