当前位置: 移动技术网 > IT编程>开发语言>Java > Spring 数据库连接池(JDBC)详解

Spring 数据库连接池(JDBC)详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

数据库连接池

对一个简单的数据库应用,由于对数据库的访问不是很频繁,这时可以简单地在需要访问数据库时,就新创建一个连接,就完后就关闭它,这样做也不会带来什么性能上的开销。但是对于一个复杂的数据库应用,情况就完全不同而,频繁的建立、关闭连接,会极大地减低系统的性能,因为对于连接的使用成了系统性能的瓶颈。

通过建立一个数据库连接池以及一套连接使用管理策略,可以达到连接复用的效果,使得一个数据库连接可以得到安全、高效的复用,避免了数据库连接频繁建立、关闭的开销。

数据库连接池的基本原理是在内部对象池中维护一定数量的数据库连接,并对外暴露数据库连接获取和返回方法。如:外部使用者可通过getconnection方法获取连接,使用完毕后再通过releaseconnection方法将连接返回,注意此时连接并没有关闭,而是由连接池管理器回收,并为下一次使用做好准备。

数据库连接池技术带来的好处:

1、资源重用

由于数据库连接得到重用,避免了频繁创建、释放链接引起的大量性能开销。在减少系统消耗的基础上,另一方面也增进了系统运行环境的平稳性(减少内存碎片以及数据库临时进行/线程数量)

2、更快地系统响应速度

数据库连接池在初始化过程中,往往已经创建了若干数据库连接池置于池中备用。此时连接的初始化工作均已完成,对于业务请求处理而言,直接利用现有可用连接,避免了数据库连接初始化和释放过程的时间开销,从而缩减了系统整体响应时间

3、统一的连接管理,避免数据库连接泄露

在较为完备的数据库连接池实现中,可根据预先的连接占用超时设定,强制收回被占用连接,从而避免了常规数据库连接操作中可能出现的资源泄露。

目前数据库连接池产品是非常多的,主要有:

1、dbcp

dbcp,即database connection poolapache出品,spring开发组推荐使用的数据库连接池,开发较为活跃,是一个使用极为广泛的数据库连接池产品。不过从网上

2、c3p0

hibernate开发组推荐使用的数据库连接池,它实现了数据源和jndi的绑定

3、proxool

proxool的口碑较好,没什么负面评价(比如dbcp就是因为hibernate认为它bug太多hibernate才不推荐使用的),也是hibernate开发组推荐使用的数据库连接池,不过使用者不算多,开发不够活跃。这个连接池提供了连接池监控的功能,方便易用,便于发现连接池泄露的情况

基于spring的jdbc基本框架搭建

先讲一下使用spring实现jdbc,数据库连接池就用spring开发组推荐的dbcp,dbcp需要三个jar包,先下载一下:

1、commons-dbcp-1.4.jar,官方网站上有,

2、commons.pool-1.6.jar,官方网站上有,

3、commons.collections4-4.0.jar,官方网站上有

下载了这三个jar包之后请导入自己的工程中(注意mysql的包别忘记导入了),虽然dbcp和pool都出了dbcp2和pool2的版本,apache官网上都可以下载,但是这里提供的还是dbcp1和pool1的版本下载地址,一个原因是dbcp2和pool2都只可以在jdk1.7及jdk1.7以上的版本运行,而dbcp1和pool1则可以在jdk1.6的版本运行,考虑到myeclipse10默认自带的jre就是1.6版本的,所以这里下载、使用dbcp1和pool1。想要dbcp2和pool2的可以自己去apache官网下载,不过要注意,dbcp2必须和pool2一组,dbcp1必须和pool1一组,不可以混着用。

jdbc,我之前写过一篇文章,数据库建立和实体类都是用的原文章里面的,这里只是把原生的jdbc搬到spring jdbc下而已,看下最基础的写法,再添加功能,学生管理类为:

public class studentmanager
{
 private jdbctemplate jdbctemplate;

 private static studentmanager instance = new studentmanager();

 public static studentmanager getinstance()
 {
 return instance;
 }

 public jdbctemplate getjdbctemplate()
 {
 return jdbctemplate;
 }
 public void setjdbctemplate(jdbctemplate jdbctemplate)
 {
 this.jdbctemplate = jdbctemplate;
 }
}

spring的xml配置文件命名为jdbc.xml,jdbc.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-4.2.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.2.xsd">

 <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource">
 <!-- 驱动包名 -->
 <property name="driverclassname" value="com.mysql.jdbc.driver" />
 <!-- 数据库地址 -->
 <property name="url" value="jdbc:mysql://localhost:3306/school?useunicode=true&characterencoding=utf8;" />
 <!-- 用户名 -->
 <property name="username" value="root" />
 <!-- 密码 -->
 <property name="password" value="root" />
 <!-- 最大连接数量 -->
 <property name="maxactive" value="150" />
 <!-- 最小空闲连接 -->
 <property name="minidle" value="5" />
 <!-- 最大空闲连接 -->
 <property name="maxidle" value="20" />
 <!-- 初始化连接数量 -->
 <property name="initialsize" value="30" />
 <!-- 连接被泄露时是否打印 -->
 <property name="logabandoned" value="true" />
 <!-- 是否自动回收超时连接 -->
 <property name="removeabandoned" value="true" />
 <!-- 超时等待时间(以秒为单位) -->
 <property name="removeabandonedtimeout" value="10" />
 </bean>

 <bean id="jdbctemplate" class="org.springframework.jdbc.core.jdbctemplate">
 <property name="datasource" ref="datasource" />
 </bean>
 <bean id="studentmanager" class="com.xrq.jdbc.studentmanager" factory-method="getinstance"> 
 <property name="jdbctemplate" ref="jdbctemplate" />
 </bean>
</beans>

主函数为:

public static void main(string[] args)
{ 
 applicationcontext ac = 
  new classpathxmlapplicationcontext("jdbc.xml");
 system.out.println(studentmanager.getinstance());
 system.out.println(studentmanager.getinstance().getjdbctemplate());
}

运行没什么问题,得到studentmanager的引用地址和studentmanager中属性jdbctemplate的引用地址,说明整个连接、注入都没问题。

jdbctemple是spring里面最基本的jdbc模板,利用jdbc和简单的索引参数查询提供对数据库的简单访问。除了jdbctemplate,spring还提供了namedparameterjdbctemplate和simplejdbctemplate两个类,前者能够在执行查询时把值绑定到sql里的命名参数而不是使用索引,后者利用java 5的特性比如自动装箱、泛型和可变参数列表来简化jdbc模板的使用。具体使用哪个看个人喜好,这里使用jdbctemplate,所以把jdbctemplate添加到学生管理类中。

另外:

1、dbcp提供很多参数给用户配置,每个参数的意思都以注释的形式写在.xml里面了,更加具体要知道每个参数的意思可以上网查询一下

2、注意dbcp的属性url,url指的是数据库连接地址,遇到特殊字符需要转义,所以这里的"&"变成了"&",不然会报错

基于spring的jdbc增删改查

上面一部分搭建了一个spring jdbc的基础框架,下面看一下java代码如何实现crud,这个过程中jdbc.xml都不需要变化。

1、添加一个学生信息,代码为:

// 添加学生信息
public boolean addstudent(student student)
{
 try
 {
 jdbctemplate.update("insert into student values(null,?,?,?)", 
  new object[]{student.getstudentname(), student.getstudentage(), student.getstudentphone()},
  new int[]{types.varchar, types.integer, types.varchar});
 return true;
 }
 catch (exception e)
 {
 return false;
 }
}

2、根据id删除指定学生信息,代码为:

// 根据id删除单个学生信息
public boolean deletestudent(int id)
{
 try
 {
 jdbctemplate.update("delete from student where studentid = ?", new object[]{id}, new int[]{types.integer});
 return true;
 }
 catch (exception e)
 {
 return false;
 }
}

3、根据id更新学生信息,代码为:

// 根据id更新指定学生信息
public boolean updatestudent(int id, student student)
{
 try
 {
 jdbctemplate.update("update student set studentname = ?, studentage = ?, studentphone = ? where studentid = ?", 
  new object[]{student.getstudentname(), student.getstudentage(), student.getstudentphone(), id},
  new int[]{types.varchar, types.integer, types.varchar, types.integer});
 return true;
 }
 catch (exception e)
 {
 return false;
 }
}

4、根据id查询学生信息,代码为:

// 根据学生id查询单个学生信息
public student getstudent(int id)
{
 try
 {
 return (student)jdbctemplate.queryforobject("select * from student where studentid = ?", 
  new object[]{id}, new int[]{types.integer}, new rowmapper<student>(){
  public student maprow(resultset rs, int arg1) throws sqlexception
  {
  student student = new student(rs.getint(1), rs.getstring(2), rs.getint(3), rs.getstring(4));
  return student;
  }
 });
 }
 // 根据id查询学生信息抛异常, 不管什么原因, 认为查询不到该学生信息, 返回null
 catch (dataaccessexception e)
 {
 return null;
 }
}

5、查询所有学生信息,代码为:

// 查询所有学生信息
public list<student> getstudents()
{
 list<map<string, object>> resultlist = jdbctemplate.queryforlist("select * from student");
 list<student> studentlist = null;
 if (resultlist != null && !resultlist.isempty())
 {
 studentlist = new arraylist<student>();
 map<string, object> map = null;
 for (int i = 0; i < resultlist.size(); i++)
 {
  map = resultlist.get(i);
  student student = new student(
  (integer)map.get("studentid"), (string)map.get("studentname"),
  (integer)map.get("studentage"), (string)map.get("studentphone")
  );
  studentlist.add(student);
  }
 }
 return studentlist;
}

这就是简单的crud操作,有了这5个作为基础,其余都可以在这5个的基础上做扩展,就不继续详细写下去了,说几个注意点:

1、个人使用经验来说,除了最后一个查询所有的以外,建议给其他的都加上try...catch...块,因为在操作失败的时候会抛出异常,捕获了就可以知道这次的操作失败了,否则只能程序终止,而自己也不知道操作到底是成功还是失败

2、添加信息、更新信息不建议把每个待操作的字段都作为形参而建议形参就是一个student实体类,这样一来更符合面向对象的设计原则,二来形参列表的字段多很容易导致出错

3、update、query方法,如果有占位符?的话,建议选择有参数类型的重载方法,指定每个占位符的字段类型,就像我上面代码写的那样

最后,这里讲的都是jdbctemplate的基本使用,jdbctemplate里面还有很多方法,就不一一细说了,可以自己去试一下,也可以查阅spring api文档。

读取配置文件中的数据

之前我们都是把数据库连接的一些属性配置在db.properties里面的,这样方便修改,而这里却是在jdbc.xml里面写死的,所以要想一个办法怎么可以从db.properties里面读取出配置,context帮助开发者实现了这一点,看一下jdbc.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-4.2.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.2.xsd">

 <context:property-placeholder location="classpath:db.properties"/>

 <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource">
 <!-- 驱动包名 -->
 <property name="driverclassname" value="${mysqlpackage}" />
 <!-- 数据库地址 -->
 <property name="url" value="${mysqlurl}" />
 <!-- 用户名 -->
 <property name="username" value="${mysqlname}" />
 <!-- 密码 -->
 <property name="password" value="${mysqlpassword}" />
 <!-- 最大连接数量 -->
 <property name="maxactive" value="150" />
 <!-- 最小空闲连接 -->
 <property name="minidle" value="5" />
 <!-- 最大空闲连接 -->
 <property name="maxidle" value="20" />
 <!-- 初始化连接数量 -->
 <property name="initialsize" value="30" />
 <!-- 连接被泄露时是否打印 -->
 <property name="logabandoned" value="true" />
 <!-- 是否自动回收超时连接 -->
 <property name="removeabandoned" value="true" />
 <!-- 超时等待时间(以秒为单位) -->
 <property name="removeabandonedtimeout" value="10" />
 </bean>

 <bean id="jdbctemplate" class="org.springframework.jdbc.core.jdbctemplate">
 <property name="datasource" ref="datasource" />
 </bean>
 <bean id="studentmanager" class="com.xrq.jdbc.studentmanager" factory-method="getinstance"> 
 <property name="jdbctemplate" ref="jdbctemplate" />
 </bean>
</beans>

重点就是第10行,第14、第16、第18、第20行就是取属性的写法,和前端的ftl语言类似。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网