请简述Spring JDBC是如何进行配置的

时间:2022-07-28
本文章向大家介绍请简述Spring JDBC是如何进行配置的,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Spring JDBC模块主要由4个包组成,分别是core(核心包)、dataSource(数据包)、object(对象包)和support(支持包)。关于这4个包的具体说明如图所示。

在Spring中,JDBC的配置是在配置文件applicationContext.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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <!-- 配置Spring的内置连接池 -->
    <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> 
        <!-- 属性注入 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///spring4"></property>
        <property name="username" value="root"></property>
        <property name="password" value="000000"></property>
    </bean>
    <!-- 配置spring的JDBC的模板 -->
    <bean id="jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref = "dataSource"></property>
    </bean>
    
    
</beans>

dataSource、jdbcTemplate和需要注入类的Bean。其中dataSource对应的org.springframework.jdbc.datasource.DriverManagerDataSource类用于对数据源进行配置,jdbcTemplate对应的org.springframework.jdbc.core.JdbcTemplate类中定义了JdbcTemplate的相关配置。上述代码中dataSource的配置就是JDBC连接数据库时所需的4个属性:

package com.yuzhou1su.jdbc.demo;
 
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
 
/*
 * JDBC模板的使用
 */
 
public class JdbcDemo {
    @Test
    public void demo() {
        //创建连接池
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql:///spring4");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("000000");
        //创建JDBC模板
        JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);
        jdbcTemplate.update("insert into account values (null,?,?)","张三",100000);
    }
 
}