zoukankan      html  css  js  c++  java
  • Spring里面c3p0连接池的配置和使用

                     Spring中C3P0配置和使用

    软件开发离不开对数据库操作,数据就像软件的血液一样,尤其在当下的信息时代。Spring作为J2EE的一站式轻量级的java开发框架当然提供了对数据库操作的封装JdbcTemplate,内部具体的实现原理就不说了,现在这里先提一提DaraSources(数据源),也可以说连接池。C3P0是我们java开发过程经常会用到的,这里总结一下spring中c3p0的配置和使用:

    1.环境搭建

    相关jar包下载地址:http://pan.baidu.com/s/1bC2V8a

      1.1 Spring相关jar包引入(共9个jar包)

        首先是配置spring容器jar:(context(上下文字段),core(spring核心包),expression(spring表达式),bean(生产和装配bean的工厂),

               common-logging(spring  中bean是从aprache引入的,所以要提供logging依赖)):

               a.spring核心容器图

                      

    、        b.spring核心容器jar支持

                     

          1.2 Spring JdbcTemplate 里面c3p0支持的 jar包引入

         a.jdbc驱动引入

         

        b.Spring jdbcTemplate的相关的jar引入

          

        c.c3p0的相关的jar引入

          

    2.数据库准备

    Source Server         : gg
    Source Host           : localhost:3306
    Source Database       : spring_database
    
    Target Server Type    : MYSQL
    File Encoding         : 65001
    
    Date: 2017-03-08 14:27:35
    */
    
    SET FOREIGN_KEY_CHECKS=0;
    
    -- ----------------------------
    -- Table structure for t_user
    -- ----------------------------
    DROP TABLE IF EXISTS `t_user`;
    CREATE TABLE `t_user` (
      `_id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(50) DEFAULT NULL,
      `userpwd` varchar(32) DEFAULT NULL,
      PRIMARY KEY (`_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of t_user
    -- ----------------------------
    INSERT INTO `t_user` VALUES ('1', 'jake', '123456');
    INSERT INTO `t_user` VALUES ('2', 'rose', '123456789');
    INSERT INTO `t_user` VALUES ('3', 'tom', '999');
    View Code

    3.编码测试

      2.1 User的标准JavaBean设计

    /**
     * 标准JavaBean
     * @author GGR
     *
     */
    public class User {
        @Override
        public String toString() {
            // TODO Auto-generated method stub
            return super.toString();
        }
        private Integer _id;//用户id
        private String username;//用户名
        private String userpwd;//用户密码
    
        public User(){}
        public User(String username,String userpwd){
            this.username = username;
            this.setUserpwd(userpwd);
        }
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getUserpwd() {
            return userpwd;
        }
        public void setUserpwd(String userpwd) {
            this.userpwd = userpwd;
        }
        public Integer get_id() {
            return _id;
        }
        public void set_id(Integer _id) {
            this._id = _id;
        }
    }
    View Code

      2.2 普通方式使用c3p0连接池

        a.1 直接在UserDao里面测试   

    import java.beans.PropertyVetoException;
    
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class UserDao {
        public static void main(String[] args) throws PropertyVetoException {
    
            /**
             * c3p0连接池数据源配置
             * 1.创建dataSources连接池对象
             * 2.初始化连接池的4项基本配置(4项基本配置是所有种类的连接池都必须配置的)
             *  a.驱动名称 DriverClass
             *  b.数据库地址 JdbcUrl
             *  c.用户名 User
             *  d.密码 Password
             */
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring_database");
            dataSource.setUser("root");
            dataSource.setPassword("362427gg");
    
            // 创建模板工具类
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(dataSource);
            
            jdbcTemplate.update("insert into t_user(username,userpwd)values(?,?)", "tom","999");
        }
    }
    View Code

        a.2. 测试结果

        

     2.3 使用c3p0连接池结合Spring容器

        a.1思路:将所有的对象创建和管理权交给spring的容器(IOC/DI)

        在src下创建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">
           
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_database"></property>
        <property name="user" value="root"></property>
        <property name="password" value="362427gg"></property>
    </bean>
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    </beans>
    View Code

        a.2编写测试代码

    package com.heima_jdbctemplate_c3p0;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    public class Testdamo {
        
        @Test
        public void demo(){
            String xmlpath = "com/heima_jdbctemplate_c3p0/bean.xml";
            ApplicationContext context = new ClassPathXmlApplicationContext(xmlpath);
            JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbctemplate");
            jdbcTemplate.update("insert into t_user(username,userpwd)values(?,?)", "tom","362427");
        }
        
    
    }
    View Code

        a.3测试结果

        

        

     2.4 使用c3p0连接池结合Spring容器(使用JdbcDaoSupport+注解+properties配置文件完成UserDao的设计)

     将配置信息直接写到spring的bean.xml显然不够灵活,我们需要将连接池配置信息写到properties文件里面,这样方便修改和维护。

      a.1 UserDao设计

    import java.util.List;
    import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
    import org.springframework.jdbc.core.support.JdbcDaoSupport;
    /**
     * 用户操作dao
     * @author GGR
     * ParameterizedBeanPropertyRowMapper提供里数据库每行每个参数到bean对象每个属性的映射
     */
    
    public class UserDao extends JdbcDaoSupport{
        public List<User> getAll(){
            return this.getJdbcTemplate().query("select* from t_user",ParameterizedBeanPropertyRowMapper.newInstance(User.class));        
        }
        
        public User QuerybyId(Integer _id){
            return this.getJdbcTemplate().queryForObject("select* from t_user where _id=?",  ParameterizedBeanPropertyRowMapper.newInstance(User.class),_id);
        }
        
    }
    View Code

      a.2 jdbcinfo.properties相关配置

    jdbc.driverClass=com.mysql.Driver
    jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring_database
    jdbc.user=root
    jdbc.password=362427gg
    View Code

      a.3 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">
    <!-- 配置数据源    -->
    <context:property-placeholder location="classpath:com/heima_jdbctemplate_c3p0/jdbcInfo.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- 扫描含有注解的包 -->
    <context:component-scan base-package="com.heima_jdbctemplate_c3p0"></context:component-scan>
    <!-- 配置jdbctemplate实例 -->
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    </beans>
    View Code

      a.4测试代码

    package com.heima_jdbctemplate_c3p0;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    public class Testdamo {
        
        @Test
        public void demo(){
            String xmlpath = "com/heima_jdbctemplate_c3p0/bean.xml";
            ApplicationContext context = new ClassPathXmlApplicationContext(xmlpath);
            UserDao dao = (UserDao) context.getBean("userdao");
            System.out.println(dao.getAll());
        }
        
    
    }
    View Code

         a.5测试结果

    总结:这里只是c3p0连接池的简单使用,主要是为了和Spring进行整合。

  • 相关阅读:
    volley框架使用
    Insert Interval
    candy(贪心)
    Best Time to Buy and Sell Stock
    Best Time to Buy and Sell Stock III
    distinct subsequences
    edit distance(编辑距离,两个字符串之间相似性的问题)
    trapping rain water
    word break II(单词切分)
    sudoku solver(数独)
  • 原文地址:https://www.cnblogs.com/ggr0305/p/6519297.html
Copyright © 2011-2022 走看看