JDBC Template簡単に使用

34731 ワード

                                                     JdbcTemplate  

JDBCはほとんどのユーザーの基本的なニーズを満たすことができますが、JDBCを使用する場合は、PreparedStatementの取得、SQL文パラメータの設定、接続の停止などのデータベースリソースを自分で管理する必要があります.
JdbcTemplateはSpringのJDBCパッケージで、JDBCをより使いやすくすることを目的としています.JdbcTemplateはSpringの一部です.JdbcTemplateはリソースの確立と解放を処理した.彼は私たちがよくある間違いを避けるのを助けてくれた.例えば、いつも接続を閉じるのを忘れた.彼はStatementの確立と実行などのコアJDBCワークフローを実行しますが、SQL文と抽出結果を提供するだけです.Springソースアドレス:https://github.com/spring-projects/spring-frameworkJdbcTemplateでSQL文を実行する方法は大きく3つに分けられます.
  • execute:すべてのSQL文を実行でき、DDL文を実行するのに一般的に用いられる.
  • update:実行用INSERTUPDATEDELETEなどのDML文.
  • queryXxx:DQLデータ問合せ文用.

  • JdbcTemplate接続プールの構成org.springframework.jdbc.core.JdbcTemplateクラスがSQL文を実行しやすい
  • public JdbcTemplate(DataSource dataSource)
      JdbcTemplate  ,    SQL  
    
         
         
         
         
  • 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文を実行しやすい
  • 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 query = jdbcTemplate.query(sql, new RowMapper() { @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); } }
  • JdbcTemplateオブジェクトのqueryメソッドを使用してRowMapper匿名内部クラスに転送
  • 匿名内部クラスで結果セットの1行のレコードを1つのProductオブジェクトに変換
  • JdbcTemplateクエリー-BeanPropertyRowMaperカスタムオブジェクトを返す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);
    }
    
    }