SSH笔记-Spring JdbcTemplate

1、作用:JDBC 模板的设计目的是为不同类型的 JDBC 操作提供模板方法. 每个模板方法都能控制整个过程, 并允许覆盖过程中的特定任务. 通过这种方式, 可以在尽可能保留灵活性的情况下, 将数据库存取的工作量降到最低

2、JdbcTemplate 类被设计成为线程安全的, 所以可以再 IOC 容器中声明它的单个实例, 并将这个实例注入到所有的 DAO 实例中

3、具名参数
①在 Spring JDBC 框架中, 绑定 SQL 参数的一种选择是使用具名参数(named parameter)
②具名参数: SQL 按名称(以冒号开头)而不是按位置进行指定. 具名参数更易于维护, 也提升了可读性. 具名参数由框架类在运行时用占位符取代
③具名参数只在 NamedParameterJdbcTemplate 中得到支持
④在 SQL 语句中使用具名参数时, 可以在一个 Map 中提供参数值, 参数名为键
也可以使用 SqlParameterSource 参数,批量更新时可以提供 Map 或 SqlParameterSource 的数组

4、文件
①Info.java:数据模型
②Detail.java:Info类引用的数据模型
③InfoDao.java:JDBC模板,用于测试模板查询
④TestMain.java:测试类
⑤db.properties:数据库配置信息
⑥jdbcTemplateContext.xml:配置文件

5、Info.java

package com.demo.sshtest;

public class Info {

    private Integer id;
    private String name;
    private String password;

    private Detail detail;

    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;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Detail getDetail() {
        return detail;
    }

    public void setDetail(Detail detail) {
        this.detail = detail;
    }

    @Override
    public String toString() {
        return "Info [id=" + id + ", name=" + name + ", password=" + password + ", detail=" + detail + "]";
    }
}

6、Detail.java

package com.demo.sshtest;

public class Detail {

    private Integer Did;
    private String Dname;
    public Integer getDid() {
        return Did;
    }
    public void setDid(Integer did) {
        Did = did;
    }
    public String getDname() {
        return Dname;
    }
    public void setDname(String dname) {
        Dname = dname;
    }
    @Override
    public String toString() {
        return "Detail [Did=" + Did + ", Dname=" + Dname + "]";
    }

}

7、InfoDao.java

package com.demo.sshtest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

//JDBC模板
@Repository
public class InfoDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Info get(Integer id){
        String sql = "select id,name,password from info where id=?";
        RowMapper<Info> rowMapper = new BeanPropertyRowMapper<>(Info.class);
        Info info = jdbcTemplate.queryForObject(sql, rowMapper,id);
        return info;
    }
}

8、TestMain.java

package com.demo.sshtest;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;


public class TestMain {

    static ApplicationContext applicationContext = null;
    static JdbcTemplate jdbcTemplate;

    public static void main(String[] args) throws Exception {
        testConnection();
        //testUpdate();
        //testBatchUpdate();
        //testQueryForObject();
        //testQueryForList();
        //testQuerySingleParam();
        //testQueryModle();
        //testNamedParameterJdbcTemplate();
        testNamedParameterJdbcTemplate2();
    }

    public static void testConnection() throws SQLException{
        applicationContext = new ClassPathXmlApplicationContext("jdbcTemplateContext.xml");
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        System.out.println(dataSource.getConnection());
        jdbcTemplate = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");
    }

    //执行 Insert、update、delete语句
    public static void testUpdate() throws SQLException{
        String sql = "Update info set name=?,password=? where id>?";
        //使用update方法,第一个属性写sql后面按照sql中?的顺序和个数写,其中数据类行要跟数据库对应
        int rs = jdbcTemplate.update(sql,"AAA","password",1);
        //update方法返回类型为int 更新多少条就返回多少
        if(rs>0){
            System.out.println("udpate success "+rs);
        }else{
            System.out.println("update failed "+rs);
        }
    }

    //批量执行Insert、update、delete语句
    public static void testBatchUpdate(){
        String sql = "Update info set name=?,password=? where id=?";
        List<Object[]> batch = new ArrayList<>();
        batch.add(new Object[]{"a","pswdA",1});
        batch.add(new Object[]{"b","pswdB",2});
        batch.add(new Object[]{"c","pswdC",4});
        //batchUpdate的两个属性,第一个是sql,第二个是Object[]数组,因为修改一条信息需要一个Object的数组,修改多条就需要多个Object的数据
        int[] rs = jdbcTemplate.batchUpdate(sql, batch);
        for(int i=0;i<rs.length;i++){
            if(rs[i]>0){
                System.out.println(i+" udpate success");
            }else{
                System.out.println(i+" update failed");
            }
        }
    } 

    //查询一条记录(实际上是返回一个Object对象)
    //注意事项:
    //1、需要使用queryForObject(String sql, RowMapper<?>rowMapper,Obect...args)的方法才能查到数据
    //2、通过RowMapper指定如何映射结果集的行,常用实现类BeanPropertyRowMapper
    //3、使用sql中列的别名完成列名和类的属性名映射
    //4、不支持级联操作
    public static void testQueryForObject(){
        String sql = "select id,name,password from info where id=?";
        RowMapper<Info> rowMapper = new BeanPropertyRowMapper<>(Info.class);
        Info info = jdbcTemplate.queryForObject(sql, rowMapper,1);
        System.out.println(info);
    }

    //查询实体类的集合
    //注意事项:调用的是query(String,RowMapper<?>rowMapper,Obect...args)方法
    public static void testQueryForList(){
        String sql = "select id,name,password from info where id>=?";
        RowMapper<Info> rowMapper = new BeanPropertyRowMapper<>(Info.class);
        List<Info> infos = jdbcTemplate.query(sql, rowMapper,1);
        System.out.println(infos);
    }

    //获取单个值或数据统计
    public static void testQuerySingleParam(){
        //数据统计
        String sql = "select count(id) from info";
        long count = jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println(count);
        //获取单个列的值
        String sql2 = "select name from info where id=?";
        String name = jdbcTemplate.queryForObject(sql2,String.class,1);
        System.out.println(name);
    }

    //模板查询
    //就是把查询的逻辑写到实体类里面,当需要使用时,使用Spring的IOC容器获取查询到的数据
    public static void testQueryModle(){
        try{
            InfoDao infoDao = (InfoDao)applicationContext.getBean("infoDao");
            System.out.println(infoDao.get(1));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //为参数起名的方式
    //好处:如果有多个参数,不需要去创建对象并在对应位置赋值,直接对应参数名即可完成赋值,便于维护
    //坏处:参数多的时候,要写的代码多,比较麻烦
    public static void testNamedParameterJdbcTemplate(){
        String sql = "update info set name=:name,password=:pswd where id=:id";
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate)applicationContext.getBean("nameParameterJdbcTemplate");
        Map<String, Object>map = new HashMap<>();
        map.put("id", 1);
        map.put("name", "XXXX");
        map.put("pswd", "passworddddd");
        namedParameterJdbcTemplate.update(sql, map);
    }

    //使用具名参数的方式
    //注意事项:
    //1、sql语句中的参数名和类的属性名要一致
    //2、使用SqlParameterSource的BeanPropertySqlParameterSource现实类作为参数
    //好处:对应着Bean中的属性,直接使用其getset方法,用起来更加清晰
    public static void testNamedParameterJdbcTemplate2(){
        String sql = "update info set name=:name,password=:password where id=:id";
        Info info = new Info();
        info.setId(2);
        info.setName("nnnnn");
        info.setPassword("pppppp");
        SqlParameterSource source = new BeanPropertySqlParameterSource(info);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate)applicationContext.getBean("nameParameterJdbcTemplate");
        namedParameterJdbcTemplate.update(sql, source);
    }
}

9、db.properties

jdbc.user=root
jdbc.password=
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost/SpringTest
jdbc.initialPoolSize=5
jdbc.maxPoolSize=10

10、jdbcTemplateContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
    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-4.3.xsd">

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置C3P0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
    <!-- 配置JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <context:component-scan base-package="com.demo.sshtest"></context:component-scan>

    <!-- 配置NamedParameterJdbcTemplate-->
    <!-- 配置该对象可以使用具名参数,其没有无参构造器,所以必须为其构造器指定参数 -->
    <bean id="nameParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"></constructor-arg>
    </bean>

</beans>

11、使用步骤:
①创建对应的bean
②写数据库连接数据的properties
③编写spring配置文件,导入资源文件
④编写spring配置文件,配置C3P0数据源
⑤编写spring配置文件,配置JdbcTemplate
⑥如果需要使用JDBC模板,则配置NamedParameterJdbcTemplate
⑦定义获取IOC容器和定义JdbcTemplate对象
⑧使用JdbcTemplate的数据库操作方法对数据库操作

12、项目目录
项目目录

13、demo
https://download.csdn.net/download/qq_22778717/10483449

猜你喜欢

转载自blog.csdn.net/qq_22778717/article/details/80718708