zoukankan      html  css  js  c++  java
  • 初识Spring JdbcTemplate

    JdbcTemplate

    概述

    JdbcTemplate是Spring提供的一个模板类,它是对jdbc的封装.用于支持持久层的操作.具有简单,方便等特点.

    pom.xml

    <!--依赖版本-->
    <properties>
        <!-- spring版本 -->
        <spring.version>5.0.2.RELEASE</spring.version>
        <!-- mysql版本 -->
        <mysql.version>5.1.30</mysql.version>
    </properties>
    
    <!--依赖包-->
    <dependencies>
        <!--spring ioc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <!--spring jdbc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <!-- mysql数据库依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    
    </dependencies>
    

    入门案例

    /**
     * spring JdbcTemplate入门案例
     */
    public class JdbcTemplateDemo {
    
        public static void main(String[] args) {
            /**
             * 需求:通过JdbcTemplate实现添加一条账户记录,到账户表account中
             */
            // 创建JdbcTemplate对象
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
    
            // 设置数据源对象
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/spring");
            dataSource.setUsername("root");
            dataSource.setPassword("root");
    
            jdbcTemplate.setDataSource(dataSource);
    
            // 添加账户信息
            jdbcTemplate.update("insert into account(name,money) values('小黄',2000)");
        }
    }
    

    SpringIOC管理JdbcTemplate

    bean.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--配置JdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <!--注入数据源对象-->
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!--配置数据源对象-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <!--注入连接数据库的四个基本要素-->
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    
    </beans>
    

    案例

    /**
     * spring JdbcTemplate入门案例
     */
    public class JdbcTemplateDemo {
    
        public static void main(String[] args) {
            /**
             * 通过spring IOC容器管理JdbcTemplate对象
             */
            // 1.加载spring配置文件,创建spring IOC容器
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean.xml");
    
            // 2.从spring IOC容器中,获取JdbcTemplate
            JdbcTemplate jdbcTemplate = (JdbcTemplate)context.getBean("jdbcTemplate");
    
            // 3.添加账户
            jdbcTemplate.update("insert into account(name,money) values('小敏',2000)");
    
        }
    }
    

    整合数据源

    在使用JdbcTemplate的时候,需要设置一个数据源对象才能完成数据库操作

    内置数据源

    <!-- 内置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--注入连接数据库的四个基本要素-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    

    c3p0数据源

    <!-- pom.xml -->
    <!--c3p0版本-->
    <c3p0.version>0.9.5</c3p0.version>
    
    <!--c3p0依赖-->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>${c3p0.version}</version>
    </dependency>
    
    
    <!-- c3p0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入连接数据库的四个基本要素-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    

    dbcp数据源

    <!-- pom.xml -->
    <!--dbcp版本-->
    <dbcp.version>1.4</dbcp.version>
    
    <!--dbcp依赖-->
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>${dbcp.version}</version>
    </dependency>
    
    
    <!-- dbcp数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <!--注入连接数据库的四个基本要素-->
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
    </bean>
    

    druid数据源

    <!-- pom.xml -->
    <!--druid版本-->
    <druid.version>1.0.29</druid.version>
    
    <!--druid依赖-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>${druid.version}</version>
    </dependency>
    
    
    <!-- druid数据源 -->
     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <!--注入连接数据库的四个基本要素-->
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
     </bean>
    

    RoeMapper

    在JdbcTemplate中query方法有一个参数:RowMapper用于对结果集进行封装

    public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException{
        return ....
    }
    

    BeanPropertyRowMapper

    Spring框架提供的RowMapper通用实现类

    // 类结构
    public class BeanPropertyRowMapper<T> implements RowMapper<T>{
        .....
    }
    
    /**
     * 关键方法一
     *		1.根据传递进来的类型信息,通过反射技术,获取类的全部成员变量,以及set方法
     *		2.把类的成员变量名称,和对应的set方法,存在集合Map中
     *		3.等待执行完成数据库操作后,把对应字段的值,赋值到对应的成员变量上
     */
    protected void initialize(Class<T> mappedClass){
        ......
    }
    
    /**
     * 关键方法二
     *		1.执行完成数据库操作后,拿到结果集ResultSet
     *		2.循环遍历ResultSet,每一行记录,调用一次该方法,进行结果集的封装
     */
     public T mapRow(ResultSet rs, int rowNumber) throws SQLException{
         ......
     }
    

    自定义RowMapper

    有时候为了代码更加简洁,会考虑使用自定义的RowMapper

    /**
     * 自定义结果集隐射:RowMapper
     */
    public class CustomRowMapper implements RowMapper<T>{
        /**
         * 实现结果集封装方法: mapRow
         * 该方法每一行结果集记录就调用一次
         */
        public T mapRow(ResultSet rs, int rowNumber) throws SQLException{
        Object object = new Object();
        
        object.setXXX(XXX);
        
        return object;
        }
    }
    

    SpringIOC案例实现

    pom.xml

    <properties>
        <!--spring版本-->
        <spring.version>5.0.2.RELEASE</spring.version>
        <!--druid版本-->
        <druid.version>1.0.29</druid.version>
        <!--mysql驱动版本-->
        <mysql.version>5.1.30</mysql.version>
    </properties>
    
    <dependencies>
        <!--spring ioc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring jdbc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--druid依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!--mysql驱动依赖-->
        <dependency>
        	<groupId>mysql</groupId>
        	<artifactId>mysql-connector-java</artifactId>
        	<version>${mysql.version}</version>
        </dependency>
    </dependencies>
    

    完全xml版本

    bean.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--配置客户service-->
        <bean id="Service" class="com.XXX.service.impl.ServiceImpl">
            <!--注入客户dao-->
            <property name="Dao" ref="Dao"></property>
        </bean>
    
        <!--配置客户dao-->
        <bean id="Dao" class="com.XXX.dao.impl.DaoImpl">
            <!--注入JdbcTemplate-->
            <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        </bean>
    
        <!--配置JdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <!--注入数据源对象-->
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!--配置数据源对象DataSource-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <!--注入四个基本属性-->
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
    
            <!--数据库连接池常用属性-->
            <!-- 初始化连接数量 -->
            <property name="initialSize" value="6" />
            <!-- 最小空闲连接数 -->
            <property name="minIdle" value="3" />
            <!-- 最大并发连接数(最大连接池数量) -->
            <property name="maxActive" value="50" />
            <!-- 配置获取连接等待超时的时间 -->
            <property name="maxWait" value="60000" />
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
        </bean>
    
    </beans>
    

    dao

    public class Dao{
        // 定义JdbcTemplate
        private JdbcTemplate jdbcTemplate;
        
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
            this.jdbcTemplate = jdbcTemplate;
        }
        
        public List<T> findAll(){
            // 定义sql
            String sql = "select * from table";
            
            // 返回执行结果
            return jdbcTemplate.query(sql, new CustomRowMapper());
        }
    }
    

    service

    public class Service{
        // 定义dao
        private Dao dao;
        
        public void setDao(Dao dao){
            this.dao = dao;
        }
        
        public List<T> findAll(){
            return dao.findAll();
        }
    }
    

    Controller

    public class Controller {
        public static void main(String[] args) {
            // 1.加载spring配置文件,创建spring容器
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean.xml");
    
            // 2.获取客户service对象
            Service Service = (Service) context.getBean("Service");
    
            // 3.查询全部客户列表数据
            List<T> list = Service.findAll();
            for(T t:list){
                System.out.println(t);
            }
        }
    }
    

    xml与注解混合版本

    bean.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.xsd">
    
        <!--配置包扫描dao/service,说明:
            第一步:导入context名称空间和约束
            第二步:通过<context:component-scan>标签配置包扫描,spring框架在
            初始化IOC容器的时候,会扫描指定的包和它的子包
        -->
        <context:component-scan base-package="com.XXX"></context:component-scan>
    
        <!--配置JdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <!--注入数据源对象-->
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!--配置数据源对象DataSource-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <!--注入四个基本属性-->
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
    
            <!--数据库连接池常用属性-->
            <!-- 初始化连接数量 -->
            <property name="initialSize" value="6" />
            <!-- 最小空闲连接数 -->
            <property name="minIdle" value="3" />
            <!-- 最大并发连接数(最大连接池数量) -->
            <property name="maxActive" value="50" />
            <!-- 配置获取连接等待超时的时间 -->
            <property name="maxWait" value="60000" />
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
        </bean>
    
    </beans>
    

    dao

    @Repository("dao")
    public class Dao{
        // 定义JdbcTemplate
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
        public List<T> findAll(){
            // 定义sql
            String sql = "select * from table";
            
            // 返回查询结果
            return jdbcTemplate.query(sql, new CustomRowMapper());
        }
    }
    

    service

    @Service("service")
    public class Service{
        // 定义dao
        private Dao dao;
        
        public List<T> findAll(){
            return dao.findAll();
        }
    }
    

    完全注解基础版本

    Spring配置类

    /**
     * 注解说明
     *		@Configuration: 标记当前java类是一个Spring的配置类
     *		@ComponentScan: 配置扫描包,相当于xml配置中<context:component-scan/>标签
     */
    @Configuration
    @ComponentScan(value = {"com.XXX"})
    public class SpringConfiguration{
    	// 配置JdbcTemplate
    	@Bean(value = "jdbcTemplate")
        public JdbcTemplate createJdbcTemplate(DataSource dataSource){
            // 创建JdbcTemplate对象
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(dataSource);
            return jdbcTemplate;
        }
        
        // 配置DataSource
        @Bean(value = "dataSource")
        public DataSource createDataSource(){
            // 创建DataSource
            DruidDataSource dataSource = new DruidDataSource();
            
            // 注入属性
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/spring");
            dataSource.setUsername("root");
            dataSource.setPassword("root");
    
            dataSource.setInitialSize(6);
            dataSource.setMinIdle(3);
            dataSource.setMaxActive(50);
            dataSource.setMaxWait(60000);
            dataSource.setTimeBetweenEvictionRunsMillis(60000);
            
            return dataSource;
        }
    }
    

    Controller

    public class Controller{
        public static void main(String[] args){
            // 1.加载Spring配置类,创建Spring容器
            ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
            
            // 2.获取service对象
            Service service = (Service)context.getBean("service");
            
            // 调用方法得到结果
            List<T> list = service.findAll();
            for(T t : list){
                System.out.println(t);
            }
        }
    }
    

    完全注解优化版本

    建立配置类之间关系

    /**
     * spring配置类:
     *  注解说明:
     *      1.@Configuration:标记当前java类,是一个spring的配置类
     *      2.@ComponentScan:配置扫描包。相当于xml配置中<context:component-scan/>标签
     *      3.@Import:导入其他模块配置类
     *      4.@PropertySource:导入属性资源文件
     */
    @Configuration
    @ComponentScan(value = {"com.XXX"})
    @Import(value={DaoConfiguration.class})
    @PropertySource(value={"classpath:jdbc.properties"})
    

    jdbc.properties

    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/spring
    jdbc.username=root
    jdbc.password=root
    
    jdbc.initialSize=6
    jdbc.minIdle=3
    jdbc.maxActive=50
    jdbc.maxWait=60000
    jdbc.timeBetweenERM=60000
    

    Dao

    public class DaoConfiguration {
    	@Bean(value="jdbcTemplate")
        public JdbcTemplate createJdbcTemplate(DataSource dataSource){
            // 创建JdbcTemplate对象
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(dataSource);
    
            return jdbcTemplate;
        }
        
        // 定义连接数据库的成员变量
        /**
         * 使用@Value注解,进行赋值
         * 使用格式:@Value("${}")
         */
        @Value("${jdbc.driverClassName}")
        private String driverClassName;
        @Value("${jdbc.url}")
        private String url;
        @Value("${jdbc.username}")
        private String username;
        @Value("${jdbc.password}")
        private String password;
    
        @Value("${jdbc.initialSize}")
        private Integer initialSize;
        @Value("${jdbc.minIdle}")
        private Integer minIdle;
        @Value("${jdbc.maxActive}")
        private Integer maxActive;
        @Value("${jdbc.maxWait}")
        private Integer maxWait;
        @Value("${jdbc.timeBetweenERM}")
        private Integer timeBetweenERM;
    
        @Bean(value="dataSource")
        public DataSource createDataSource(){
            // 创建DataSource
            DruidDataSource dataSource = new DruidDataSource();
    
            // 注入属性
            // 注入属性
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
    
            dataSource.setInitialSize(initialSize);
            dataSource.setMinIdle(minIdle);
            dataSource.setMaxActive(maxActive);
            dataSource.setMaxWait(maxWait);
            dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenERM);
    
            return dataSource;
        }
    }
    
  • 相关阅读:
    The Chinese Postman Problem HIT
    Chinese Postman Problem Aizu
    矩阵游戏 HYSBZ
    最大获利 HYSBZ
    asp.net+MVC--1
    -----IT男生涯————初始篇
    Permutation
    RMQ with Shifts
    Fast Matrix Operations
    "Ray, Pass me the dishes!"
  • 原文地址:https://www.cnblogs.com/unrecognized/p/11622700.html
Copyright © 2011-2022 走看看