SptingJDBCTemplat的基本使用

一、数据库连接池

1.连接池

1.1连接池介绍

技术是把数据库的连接对象缓存到一个容器中,减少了重复创建和关闭连接对象Connection造成性能损耗,当需要连接对象时,从连接池中获取一个,使用完成后归还到连接池中,以重复利用该连接对象,如果连接池中没有可用的连接对象,那么线程将等待

连接池技术 中使用的连接对象并不是 原始的java.sql.Connection ,一般为它的子类型,该类型重写

close(),这个关闭并不是关闭这个连接对象,而是把这个连接对象归还给连接池。

1.2 实现连接池原理
package com.qfedu.jdbc;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

//自定义连接池
public class MyPool {
    //准备一个集合
    static LinkedList<PoolConnection> connections = new LinkedList<>();
    // 初始化连接池( 默认有4个连接对象 )
    static{
        // 初始化几个连接对象
        for (int i=0;i<4;i++){
            try {
                //原生Conn
              Connection conn =    DriverManager.getConnection("jdbc:mysql://localhost:3306/empdb?useSSL=false","root","123456");
                //包装后的Conn
              PoolConnection connection = new PoolConnection(conn);
              // 添加到连接池
              connections.add(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //装饰模式:在不改变现有类的基础上,扩展或者整强该类的功能。
    //在连接池技术中,Connection 需要被装饰。
    //增强close方法
    //提供一个方法,重连接池中获得连接对象
    public static Connection getConnection(){
      Connection conn =   connections.removeFirst(); // 从连表的头部获取一个连接对象
      return conn;
    }

测试方法

 public static void main(String[] args) {

        for(int i=0;i<1000;i++) {
            Connection con = MyPool.getConnection();
            System.out.println(con+":"+i);

            PoolConnection obj = (PoolConnection) con;
            try {
                obj.close(connections);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

二、Druid连接池

1.druid连接池

数据库连接池实现技术,由阿里巴巴提供的,目前比较主流

  1. 步骤:

    1. 导入jar包 druid-1.1.0.jar

      1. 定义配置文件:

        • 是properties形式的
          • 可以叫任意名称,可以放在任意目录下
        1. 加载配置文件。Properties
        2. 获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory
        3. 获取连接:getConnection

Druid:数据库连接池实现技术,由阿里巴巴提供的

package DruidDemo;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Properties;

/**
 * druid连接池的使用
 * @param
 * @return
 */
public class DruidDemo01 {
    /**
     * 使用工厂构建者模式
     * @throws Exception
     */
   @Test
    public  void test01() throws Exception {
        Properties properties = new Properties();
        properties.load(DruidDemo01.class.getClassLoader().getResourceAsStream("druid.properties"));
        //使用工厂创建并且传入配置文件   工厂构建者模式   返回的实际上是DataSource的子类DruidDatasource
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection conn = dataSource.getConnection();
        System.out.println(conn);
    }


    /**
     * 使用new的方式
     * @throws Exception
     */
    @Test
    public void test02()throws Exception{
        Properties properties = new Properties();
        properties.load(DruidDemo01.class.getClassLoader().getResourceAsStream("druid2.properties"));
        DruidDataSource ds = new DruidDataSource();
        ds.configFromPropety(properties);
        Connection connection = ds.getConnection();
        System.out.println(connection);
    }
}

druid2.properties配置文件

driverClassName=com.mysql.jdbc.Driver
username=root
password=123
url=jdbc:mysql://localhost:3306/jdbcdemo
initialSize=5

注:使用new的形式druid-1.0.9.jar不支持,所以以后尽量使用工厂构件模式

三、Spring JDBC

1.JDBCTemplate

Spring框架对JDBC的简单封装,提供了一个JDBCTemplate对象简化JDBC的开发

2.实现步骤

​ 1、导入jar包

	1. 导入jar包
	2. 创建JdbcTemplate对象。依赖于数据源DataSource
		* JdbcTemplate template = new JdbcTemplate(ds);

	3. 调用JdbcTemplate的方法来完成CRUD的操作
		* update():执行DML语句。增、删、改语句
		* queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
			* 注意:这个方法查询的结果集长度只能是1
		* queryForList():查询结果将结果集封装为list集合
			* 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
		* query():查询结果,将结果封装为JavaBean对象
			* query的参数:RowMapper
				* 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
				* new BeanPropertyRowMapper<类型>(类型.class)
		* queryForObject:查询结果,将结果封装为对象
			* 一般用于聚合函数的查询

入门和实现

dao持久层

package JDBCTemplate;
import DataSourceUtil.DataSourceUtil;
import JDBCTemplate.domain.Car;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;

/**
 * @param
 * @return
 */
public class JDBCTemplate {
    public static void main(String args[]){

        //传入连接池创建JdbcTemplate
        JdbcTemplate template = new JdbcTemplate(DataSourceUtil.getDataSource());
        //添加数据
        int row = template.update("insert into sys_cars(carname,pl,cartype) value(?,?,?)", "赤兔马", "无上限", 9999999);
        System.out.println(row);

        //查询单个
        Car car = template.queryForObject("select * from sys_cars where id = ? ", new BeanPropertyRowMapper<>(Car.class),1);
        System.out.println(car);

        //查询所有
        List<Car> cars = template.query("select * from sys_cars", new BeanPropertyRowMapper<>(Car.class));
        for (Car car1 : cars) {
            System.out.println(car1);
        }
    }

}

实体类

package JDBCTemplate.domain;

import java.io.Serializable;
import java.util.Date;

/**
 * car的实体类
 * @param
 * @return
 */
public class Car implements Serializable {
    private Integer id; //id编号自动增长
    private String carName;//车名
    private String pl; //排量T表示涡轮增压 L表示自然吸气
    private String carType;//类型比如 轿车 svm mpv
    private Double price;//售价
    private Integer mileage;//里程数
    private Date productionDate;//出厂日期
    private String serial;//车架号

    public Car() {
    }

    public Car(Integer id, String carName, String pl, String carType, Double price, Integer mileage, Date productionDate, String serial) {
        this.id = id;
        this.carName = carName;
        this.pl = pl;
        this.carType = carType;
        this.price = price;
        this.mileage = mileage;
        this.productionDate = productionDate;
        this.serial = serial;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }

    public String getPl() {
        return pl;
    }

    public void setPl(String pl) {
        this.pl = pl;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Integer getMileage() {
        return mileage;
    }

    public void setMileage(Integer mileage) {
        this.mileage = mileage;
    }

    public Date getProductionDate() {
        return productionDate;
    }

    public void setProductionDate(Date productionDate) {
        this.productionDate = productionDate;
    }

    public String getSerial() {
        return serial;
    }

    public void setSerial(String serial) {
        this.serial = serial;
    }

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", carName='" + carName + '\'' +
                ", pl='" + pl + '\'' +
                ", carType='" + carType + '\'' +
                ", price=" + price +
                ", mileage=" + mileage +
                ", productionDate=" + productionDate +
                ", serial='" + serial + '\'' +
                '}';
    }
}

连接池工具类

package DataSourceUtil;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * 连接池的工具类
 * @param
 * @return
 */
public class DataSourceUtil {
    //声明一个连接池的引用
    private static DataSource dataSource = null;
    //获得连接池的方法
    public synchronized static DataSource getDataSource(){
        //连接池为空
        if(dataSource==null){
            //使用Druid 连接池
            DruidDataSource druidDataSource = new DruidDataSource();
            //配置连接池。
            Properties pro = new Properties();
            //加载配置文件。
            try {
                pro.load(  Thread.currentThread().getContextClassLoader().getResourceAsStream("druid2.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            druidDataSource.configFromPropety(pro);// 通过一个Properties对象完成配置
            druidDataSource.setMaxWait(5000);// 找配置
            dataSource = druidDataSource;
        }
        return dataSource;
    }
}

posted @ 2020-04-21 00:47  熬夜总冠军  阅读(363)  评论(0编辑  收藏  举报