Spring JdbcTemplate基本使用

Spring JdbcTemplate基本使用

文章目录

1.JdbcTemplate概述

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

2. JdbcTemplate开发步骤

① 导入spring-jdbc和spring-tx坐标
② 创建数据库表和实体
③ 创建JdbcTemplate对象
④ 执行数据库操作

3.快速入门

1.导入坐标

  • spring-context
  • c3p0
  • junit
    -spring-test
  • mysql-connector-java
  • spring-jdbc
  • spring-tx
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>

2.创建表account和实体类Account

建表sql:

CREATE TABLE account(
`oid` int NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(10) NOT NULL,
`money` int NOT NULL,
PRIMARY KEY(`oid`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

pojo类:

package com.itspring.pojo;

public class Account {
    private int oid;
    private String username;
    private int money;

    public int getMoney() {
        return money;
    }

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

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

3.创建JdbcTemplate对象,执行数据库操作

package test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.beans.PropertyVetoException;
import java.sql.SQLException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class TestJdbcTemplate {

    //手动创建JdbcTemplate对象
    @Test
    public void test1() throws SQLException, PropertyVetoException {
        //创建c3p0数据库连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        //设置连接参数
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUser("root");
        dataSource.setPassword("root");
        //创建jdbcTemplate对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //给jdbcTemplate对象设置数据源
        jdbcTemplate.setDataSource(dataSource);
        //插入一条数据
        int i = jdbcTemplate.update("insert into account values(?,?,?)", 1, "tom", 2000);
        System.out.println(i);

    }
}

Spring JdbcTemplate基本使用Spring JdbcTemplate基本使用

4. Sprin*生JdbcTemplate对象

我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模版对象中.

1.创建jdbc.prperties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.user=root
jdbc.password=root

2.配置spring-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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--引入jdbc.properties-->
    <context:property-placeholder location="jdbc.properties"/>
    <!--配置c3p0连接池-->
    <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.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--配置jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

3.在applicationContext.xml中引入spring-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="classpath:spring-jdbc.xml"/>
</beans>

4.创建SpringJunit测试类,并将jdbcTemplate注入

package test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.beans.PropertyVetoException;
import java.sql.SQLException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class TestJdbcTemplate {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //Spring创建jdbcTemplate对象
    @Test
    public void test2() {
        //插入一条数据
        int i = jdbcTemplate.update("insert into account values(?,?,?)", 3, "lucy", 5000);
        System.out.println(i);
    }
}

Spring JdbcTemplate基本使用
Spring JdbcTemplate基本使用

5. JdbcTemplate常用操作

5.1 CURD操作

注意:
1.如果pojo中没有get/set,那么Springjdbc映射时会找不到属性值,从而为null
2.BeanPropertyRowMapper是RowMapper的实现类
public class BeanPropertyRowMapper<T> implements RowMapper<T>

    //常用操作操作
    @Test
    public void test3() {
        int i = 0;
        //更新操作
        i = jdbcTemplate.update("update account set money=? where username =?", 1000, "tom");
        System.out.println("update:" + i);
        //删除操作
        i = jdbcTemplate.update("delete from account where oid = ?", 1);
        System.out.println("delete:" + i);
        //查询全部
        List<Account> accounts = jdbcTemplate.query("select * from account",
                new BeanPropertyRowMapper<Account>(Account.class));
        AtomicInteger j = new AtomicInteger(1);
        accounts.forEach((s) -> {
            System.out.println("第" + (j.getAndIncrement()) + "条:" + s);
        });
        //查询单个
        Account account = jdbcTemplate.queryForObject("select * from account where username = ?",
                new BeanPropertyRowMapper<Account>(Account.class),"cat");
        System.out.println("查询单个" + account);

    }

Spring JdbcTemplate基本使用

Spring JdbcTemplate基本使用

上一篇:DUBBO源码分析五---服务引用


下一篇:JDBCTemplate操作数据库