Spring JDBC的详解

一.Spring jdbc概述

1.概述:

Spring JDBC是Spring所提供的持久层技术,他主要目的降低JDBC API的使用难度,以一种更直接、更简洁的方式使用JDBC API。

2.作用:

Spring的JDBC模块负责数据库资源和错误处理,大大简化了开发人员对数据库的操作。

3.包:
  • core:核心包,包含了JDBC的核心功能。例如jdbcTemplate类
  • datasource:数据源包
  • object:对象包
  • support:支持包。是core包和object包的支持类。

二.Spring jdbc的配置

针对mysql数据库,有以下四种配置:

1.使用org.springframework.jdbc.datasource.DriverManagerDataSource

使用 DriverManagerDataSource建立连接是只要有连接就新建一个connection,根本没有连接池的作用。

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
     <!-- spring管理jdbc和数据库连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="url" value="jdbc:mysql:///shop"></property>
     </bean>
    <!-- spring管理jdbc模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>
2.使用org.apache.commons.dbcp.BasicDataSource

需要下载的jar包:commons-dbcp.jar,commons-pool.jar
说明:这是一种推荐说明的数据源配置方式,它真正使用了连接池技术

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">

     <!-- spring管理dbcp数据库连接池-->

    <bean  id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="url" value="jdbc:mysql:///shop"></property>
        <property name="maxActive" value="20"></property>
        <property name="maxIdle" value="5"></property>
        <property name="minIdle" value="2"></property>
        <property name="maxWait" value="10000"></property>
    </bean>
    <!-- spring管理jdbc模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>
3.spring管理c3p0数据库连接池

注意:这种方法中用了$(username)之后好像会取当前计算机用户名来连接数据库,将db.properties中的username改成user就可以了。

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">

     <!-- spring管理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:///shop"></property>
      <property name="password" value="root"></property>
      <property name="user" value="root"></property>
  </bean>
    <!-- spring管理jdbc模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>
4. 使用hibernate数据源

需要hiberante核心jar包。
目前三大框架较流行,spring一般与hiberante做搭档,数据库连接方式写在hiberante的配置文件中,在spring管理hibernate中的配置文件中,直接读取hibernate核心配置文件即可。

[html]  
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">   
<property name="configLocations">   
<list>   
<value>classpath:com/config/hibernate.cfg.xml</value>   
</list>   
</property>   
<property name="mappingLocations">   
<!-- 所有的实体类映射文件 -->   
<list>   
<value>classpath:com/hibernate/hbm.xml</value>   
</list>   
</property>   
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
 <property name="configLocations">  
   <list>  
      <value>classpath:com/config/hibernate.cfg.xml</value>  
   </list>  
 </property>  
    <property name="mappingLocations">   
<!-- 所有的实体类映射文件 -->  
        <list>  
            <value>classpath:com/hibernate/hbm.xml</value>  
        </list>  
</property>  
 

三.jdbcTemplate

1.引入

Spring对数据库的操作在jdbc上面做了深层次的封装,使用Spring的注入功能,可以吧DataSource注册到jdbcTemplate中

2.jdbcTemplate更新数据库的常用方法
  • update(更新数据,即数据的增删改)
  • batchUpdate(批量更新数据库)
  • queryForObject(查询单行)
  • query(查询多行)
  • queryForObject(查询单值)
3.数据库连接池的优点
  • 资源重用,避免频繁创建
  • 更快的系统反应速度
  • 实现某一应用最大可用数据库连接数的限制避免某一应用独占所有资源
  • 统一的连接管理,避免数据库连接池链接泄露
4.Spring中实现jdbcTemplate对数据库操作

(1).导入jar包
(2).src下创建属性配置文件db.properties

driverClass=com.mysql.jdbc.Driver
#url=jdbc:mysql://localhost:3306/shop
url=jdbc:mysql://localhost:3306/shop
#username=root
user=root
password=root

(3).配置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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <!-- 引入工程中src下的db.properties文件1-->
    <!-- 1 可以 <property name="location" value="db.properties"></property>-->
    <!-- 2 不可以<property name="location"  value="classpath*:db.properties"></property>-->
<!--    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->
<!--        <property name="location" value="classpath:db.properties"></property>-->
<!--    </bean>-->

    <!-- 引入工程中src下的db.properties文件2-->
 <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

     <!-- spring管理c3p0数据库连接池-->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
      <property name="driverClass" value="${driverClass}"></property>
      <property name="jdbcUrl" value="${url}"></property>
      <property name="password" value="${password}"></property>
      <property name="user" value="${user}"></property>
  </bean>
    <!-- spring管理jdbc模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

bean类:

package com.it.spring.jdbc;
 
public class Account {

    private Integer id;
    private String name;
    private Double money;

    public Account() {
    }

    public Account(Integer id, String name, Double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }
}

测试类

package com.it.spring.jdbc;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration("classpath:applicationContext.xml")
public class SpringJDBCTest1 {
  @Resource
 JdbcTemplate jdbcTemplate;
 /*由于jdbcTemplate在内部通过PreparedStatament执行SQL语句,所有可以绑定参数的SQL语句,每个"?"占位符可以接受一个参数*/

  @Test
  public void addAccount(){
     jdbcTemplate.update("insert into account(id,name,money)values(?,?,?)",5,"admin1",9100L);
      System.out.println("--------操作成功!-----------");

  }
    @Test
    public void updateAccount(){
        jdbcTemplate.update("update account set name=?,money=? where id=?","wwe",19100L,5);
        System.out.println("--------操作成功!-----------");

    }
    @Test
    public void delAccount(){
        jdbcTemplate.update("delete  from account where id=?",5);
        System.out.println("--------操作成功!-----------");

    }
    //查询某个属性
    @Test
    public void findNameAccount(){
      String name = jdbcTemplate.queryForObject("select name  from account where id=?",String.class,4);
        System.out.println("name-->"+name);
        System.out.println("--------操作成功!-----------");

    }

    //查询某个属性
    @Test
    public void countAccount(){
        Long count = jdbcTemplate.queryForObject("select count(*)  from account",Long.class);
        System.out.println("count-->"+count);
        System.out.println("--------操作成功!-----------");

    }
    //查询返回对象或集合

     @Test
    public void findAccountById(){
     Account account =  jdbcTemplate.queryForObject("select * from account where id=?",new MyRowMapper(),4);
       if(account!=null){
           System.out.println(account);
       }
    }

    @Test
    public void queryAllAccount(){
        List<Account> accounts = jdbcTemplate.query("select * from account",new MyRowMapper());
        for (Account account :accounts) {
            System.out.println(account);
        }
    }


    //定义内部类
    class MyRowMapper implements  RowMapper<Account>{
        @Override
        public Account mapRow(ResultSet resultSet, int i) throws SQLException {
            Account account = new Account();
            account.setId(resultSet.getInt("id"));
            account.setMoney(resultSet.getDouble("money"));
            account.setName(resultSet.getString("name"));
            return account;
        }
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值