jdbcTemplate 基本配置

  jdbcTemplate涉及到的内容很多,再结合spring和数据库来看地话,所涵盖的点就更为复杂。本篇只是作为一个开端,创建一套简洁有效的数据库连接的代码,后续还会有更多的关于各种spring配置,连接参数,以及数据库基础的知识进行分门别类进行分析,消化。

  工程结构:

  

  dao中定义了一个简单的查询操作,关于jdbcTemplate的各种查询方法,后续也会详细讨论,这里这是为了搭建这一套简易框架。

package com.changjiang.test.jdbcTemplate.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class VideoSecuriteDaoImpl {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final Logger log = LoggerFactory.getLogger(VideoSecuriteDaoImpl.class);

    public List<Map<String,Object>> getSecuriteMap(int pageSize, int pageNo) {
        List<Map<String,Object>> list = new ArrayList<>();
        if (pageSize != 0) {
            String sql = "select camillo,encode from video_securities where is_use = 0 limit " + (pageNo - 1) * pageSize
                    + "," + pageSize;
            try {
                list = jdbcTemplate.queryForList(sql);
            } catch (DataAccessException e) {
                log.error("查询VideoSecurite中camillo,encode报错: " + e.toString());
            }
        }
        return list;
    }
}

这里实现了一个分页查询,App.java的任务是选择profile,加载配置文件,以及简单测试dao查询的内容:

package com.changjiang.test.jdbcTemplate;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.changjiang.test.jdbcTemplate.dao.VideoSecuriteDaoImpl;

/**
 * Hello world!
 *
 */
public class App {
    private static Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        System.setProperty("spring.profiles.active", "production");
        logger.info("===========================================================================");
        logger.info("                     服务将在[{}]环境启动                  ", "production");
        logger.info("===========================================================================");
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        ac.start();
        VideoSecuriteDaoImpl videoSecuriteDaoImpl = ac.getBean(VideoSecuriteDaoImpl.class);
        List<Map<String, Object>> list = videoSecuriteDaoImpl.getSecuriteMap(1000, 1);
        for (Map<String, Object> map : list) {
            System.out.println(map.get("camillo"));
        }
        ac.close();
    }
}

在applicationContext.xml中只定义了一个profile,即production,实际开发中可以根据开发,测试和发布的需要配置不同的profile,切换时只需要改一个jar文件的输入参数即可,看看该文件的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p" xmlns="http://www.springframework.org/schema/beans"
    xmlns:c="http://www.springframework.org/schema/c" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:cache="http://www.springframework.org/schema/cache"
    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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd"
    default-lazy-init="true">

    <description>Spring公共配置</description>

    <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->
    <context:annotation-config />

    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    <context:component-scan base-package="com.changjiang.test.jdbcTemplate" />
    <!-- spring-jdbc -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 使用annotation定义事务 -->
    <tx:annotation-driven proxy-target-class="true" />
    <bean id="transactionManager" name="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>
    <!-- 定义事务规则 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
    <!-- 声明事务 -->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="transactionPointcut"
            expression="execution(* com.changjiang.test.jdbcTemplate.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="transactionAdvice" />
    </aop:config>

    <!-- production环境 -->
    <beans profile="production">
        <context:property-placeholder
            ignore-unresolvable="true" location="classpath*:/application.properties" />
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
            init-method="init" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="5" />
            <property name="maxActive">
                <value>${jdbc.pool.maxActive}</value>
            </property>
            <property name="minIdle">
                <value>${jdbc.pool.minIdle}</value>
            </property>
            <property name="maxWait">
                <value>${jdbc.pool.maxWait}</value>
            </property>
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="300000" />
            <!-- 打开removeAbandoned功能 -->
            <property name="removeAbandoned" value="true" />
            <!-- 1800秒,也就是30分钟 -->
            <property name="removeAbandonedTimeout" value="1800" />
            <!-- 关闭abanded连接时输出错误日志 -->
            <property name="logAbandoned" value="true" />
            <property name="timeBetweenLogStatsMillis" value="300000" />
            <!-- 加密 -->
            <property name="connectionProperties" value="config.decrypt=true" />
            <property name="proxyFilters">
                <list>
                    <ref bean="logFilter" />
                </list>
            </property>
            <property name="filters" value="stat,config,wall,slf4j,log4j" />
        </bean>
        <bean id="logFilter" class="com.alibaba.druid.filter.logging.Log4jFilter">
            <property name="statementExecutableSqlLogEnable" value="false" />

            <property name="statementLoggerName" value="sqlLogger" />
            <!--<property name="resultSetLogEnabled" value="false" /> -->
        </bean>
    </beans>
</beans>

  在该配置中有许多点,可以作为专门的小节来分析,在这里,需要注意的是,在所有的数据加载进spring容器之前,需要激活对应的剖面--profile,App.java中提供了一种方式,它会先将production激活,并在指定的位置找到各个属性对应的值,再将bean加载到spring容器之中,否则会出现org.springframework.beans.factory.NoSuchBeanDefinitionException。这是在Spring3.1之后新增加的功能,关于它的详细用法,看下一篇Spring之Environment。

时间: 2024-08-11 03:30:38

jdbcTemplate 基本配置的相关文章

JdbcTemplate模板配置及使用

接数据源的配置..... <!-- 配置Jdbc模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务管

springboot之多数据源配置JdbcTemplate

springboot多数据源配置,代码如下 DataSourceConfig package com.rookie.bigdata.config; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.

Spring(四)-- JdbcTemplate、声明式事务

1.Spring提供的一个操作数据库的技术JdbcTemplate,是对Jdbc的封装.语法风格非常接近DBUtils. JdbcTemplate可以直接操作数据库,加快效率,而且学这个JdbcTemplate也是为声明式事务做准备,毕竟要对数据库中的数据进行操纵! JdbcTemplate中并没有提供一级缓存,以及类与类之间的关联关系!就像是spring提供的一个DBUtils. Spring对数据库的操作使用JdbcTemplate来封装JDBC,结合Spring的注入特性可以很方便的实现对

Spring中使用JdbcTemplate

软件152班杨锦宏 Spring中使用JdbcTemplate.JdbcDaoSupport和NamedParameterJdbcTemplate来操作数据库,但是JdbcTemplate最常用,最易用. jdbc.properties: user=root password=123 driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc\:mysql\:///spring?encoding\=UFT-8 initPoolSize=5 maxPoolSize

Spring AOP根据JdbcTemplate方法名动态设置数据源

说明:现在的场景是,采用数据库(Mysql)复制(binlog)的方式在两台不同服务器部署并配置主从(Master-Slave)关系: 并需要程序上的数据操作方法来访问不同的数据库,比如,update方法访问主数据库服务器,query方法访问从数据库服务器. 即把"增删改"和"查"分开访问两台服务器,当然两台服务器的数据库同步事先已经配置好. 然而程序是早已完成的使用Spring JdbcTemplate的架构,如何在不修改任何源代码的情况下达到<本文标题&g

Spring jdbcTemplate RowMapper绑定任意对象

RowMapper可以将数据中的每一行封装成用户定义的类,在数据库查询中,如果返回的类型是用户自定义的类型则需要包装,如果是Java自定义的类型,如:String则不需要,Spring最新的类SimpleJdbcTemplate使用更加简单了.下面这个实例说明了如何使用RowMapp,从网上下载的代码,还行能说明问题.在使用过程中我们可以将内部类做成POJO的外部类,只要实现RowMapper接口即可.如果用户想让ApplicationContext进行定义还是要谨慎.毕竟实现RowMapper

Spring Boot整合JdbcTemplate访问数据库

这篇文章是介绍 Spring Boot整合JdbcTemplate,配置数据源来访问数据库. 在pom文件里添加 spring-boot-starter-jdbc 和mysql依赖. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency> <dep

SpringBoot2.0 基础案例(07):集成Druid连接池,配置监控界面

一.Druid连接池 1.druid简介 Druid连接池是阿里巴巴开源的数据库连接池项目.Druid连接池为监控而生,内置强大的监控功能,监控特性不影响性能.功能强大,能防SQL注入,内置Loging能诊断Hack应用行为.Druid连接池是阿里巴巴内部唯一使用的连接池,在内部数据库相关中间件TDDL/DRDS 都内置使用强依赖了Druid连接池,经过阿里内部数千上万的系统大规模验证,经过历年双十一超大规模并发验证. 2.druid特点 1)稳定性特性,阿里巴巴的业务验证 2)完备的监控信息,

JdbcTemplate经典案例

一.JdbcTemplate案例配置式 (1)导入依赖 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>mysql<