Maxon's Blog

JDBCTemplate 基本使用

5

1.1 JDBCTemplate概述

它是Spring框架中提供的一个对象,是对原始繁琐的JDBCAPI对象的简单封装, Spring框架为我们提供了很多的操作模板类.例如:操作关系型数据库的JDBCTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate

1.2 JDBCTemplate开发步骤

  • 导入Spring-jdbc 和spring-tx的坐标

    Xml
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.23</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.3.23</version>
    </dependency>
    
  • 创建数据库表和实体

  • 创建JDBCTemplate对象

  • 执行数据库操作

    Java
    @Test
    //测试JDBC模板开发步骤
    public void test1() throws PropertyVetoException {
        //创建数据源对象
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://url/learnSpring");
        dataSource.setUser("usr");
        dataSource.setPassword("pwd");
    
    
        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        //设置数据源对象  知道数据库在哪
        jdbcTemplate.setDataSource(dataSource);
    
        //执行操作
        int row = jdbcTemplate.update("insert into account values(?,?)", "Aealen", 5000);
        System.out.println(row);
    
    }
    

1.3 Spring 产生JDBCTemplate对象

可以将JDBCTemplate的创建权交给Spring,将数据源DataSource也交给Spring,在Spring容器中将数据源DataSource注入到JdbcTemplate模板对象中

Java
@Test
//测试Spring产生JDBC模板对象
public void test2() {
    ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
    JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);
    int row = jdbcTemplate.update("insert into account values(?,?)", "Aealen", 5000);
    System.out.println(row);
}
Xml
 <!--加载外部JDBC.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!--数据源对象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--JDBC模板对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>