美文网首页
Spring JDBC 框架

Spring JDBC 框架

作者: weihy | 来源:发表于2019-11-03 10:45 被阅读0次

本文摘抄至实验楼教程:https://www.shiyanlou.com/courses/578/learning/?id=1941

 Spring 框架的核心思想就是建立一个Java对象的大工厂,用户只需要给工程一个指令,工厂就能将用户需要的对象根据配置文件组装好返还给yonghu用户。用户需要做的许多工作则可以写成简单的配置文件。
 传统的使用JDBC的方法,有时候需要结合复杂的SQL语句,还需要去拼装,稍微不注意就有可能出错。Spring JDBC Template正是简化了上述的麻烦而设计出来的。它是对Java原生JDBC的封装,抽象我们常用的一些方法。

 Spring JDBC Template使用Spring的注入功能,可以把DataSource注册到JdbcTemplate之中,其全限定命名为org.springframework.jdbc.core.JdbcTemplate;还需要使用一个Spring的spring-tx包,这个包含了事务管理和异常控制。

 JdbcTemplate主要提供以下五类方法:

  1. execute方法 —— 可以用于执行任何SQL语句,一般执行DDL语句(CREATE TABLE/VIEW/INDEX/SYN/CLUSTER)
  2. update —— update方法用于执行新增、更新、删除等操作,即DML语句(INSERT/UPDATE/DELETE)
  3. batchUpdate方法 —— batchUpdate方法用于执行批处理相关语句。
  4. queryqueryForXXX方法 —— 用于执行查询相关语句,DQL语句。
  5. call方法 —— 用于执行存储过程、函数相关语句。

下面学习如何使用Spring JdbcTemplate实现对数据库的增删改查。

1、数据库准备

本文需要使用数据库,选择使用Mysql,安装教程略过请自行查询相关教程。
创建一个jdbc的数据库,下图:


mysql.png

创建学生表student并插入一条数据:

USE `jdbc`;

CREATE TABLE `student`(`id` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(16),
`age` INT) ;

INSERT INTO `student` VALUES(1,"weihouye",23);



查询结果:

查询结果.png
2、新增项目

首先创建一个maven工程SpringJdbc,对应pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.shiyanlou.jdbc</groupId>
  <artifactId>SpringJdbc</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>SpringJdbc</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>5.1.1.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>



现在src/main路径下新建目录resources,可以在里面新建Spring bean的配置文件,创建SpringBeans.xml,配置bean如下:

<?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">

    <context:annotation-config/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:23306/jdbc"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>
3、Spring JdbcTemplate 增

最后在src/shiyanlou/jdbc创建App.java

package com.shiyanlou.jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Hello world!
 *
 */
public class App 
{
    private static ApplicationContext context;
    public static void main( String[] args )
    {
        context = new ClassPathXmlApplicationContext("SpringBeans.xml");

        JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");
        String sql = "insert into student value(?,?,?)";
        int count = jt.update(sql, 2,"yangzhan",23);
        System.out.println(count);
    }
}

运行结果返回:1 ;数据库中student表中的数据:

image.png
4、Spring JdbcTemplate 删

JdbcTemplate删除数据还是可以通过update()方法实现,修改App.java如下:

package com.shiyanlou.jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Hello world!
 *
 */
public class App 
{
    private static ApplicationContext context;
    public static void main( String[] args )
    {
        context = new ClassPathXmlApplicationContext("SpringBeans.xml");

        JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");
//        String sql = "insert into student value(?,?,?)";   //增
        String sql = "Delete from `student` where id = ?";
        int count = jt.update(sql,2);
        System.out.println(count);
    }
}

运行打印:1;查看数据库发现,id=2 的数据被删除了:


image.png
5、Spring JdbcTemplate 改

JdbcTemplate 修改数据还是通过update()方法实现的,如下:

package com.shiyanlou.jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Hello world!
 *
 */
public class App 
{
    private static ApplicationContext context;
    public static void main( String[] args )
    {
        context = new ClassPathXmlApplicationContext("SpringBeans.xml");

        JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");
//        String sql = "insert into student value(?,?,?)";   //增
//        String sql = "Delete from `student` where id = ?";  //删
        String sql = "update `student` set name = ? ,age = ? where id = ?";
        int count = jt.update(sql,"weihouye2",24,1);
        System.out.println(count);
    }
}

运行返回:1 ;查看数据库:id=1 的数据已经被修改。


image.png
6、Spring JdbcTemplate 查

JdbcTemplate查询数据可以通过queryForObject和query来实现,前者用来查询单条数据,后者用来查询多条数据。

 6.1、查询单条数据

首先定义一个Student.java类,用于映射数据库对象,如下:

package com.shiyanlou.jdbc;

/**
 * Created by Administrator on 2019/11/3.
 */
public class Student {
    private int id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

修改App.java代码如下:

package com.shiyanlou.jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 * Hello world!
 *
 */
public class App 
{
    private static ApplicationContext context;
    public static void main( String[] args )
    {
        context = new ClassPathXmlApplicationContext("SpringBeans.xml");

        JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");
//        String sql = "insert into student value(?,?,?)";   //增
//        String sql = "Delete from `student` where id = ?";  //删
//        String sql = "update `student` set name = ? ,age = ? where id = ?"; //改

        String sql = "select * from student";

        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
        Student stu = jt.queryForObject(sql,rowMapper);
        System.out.println(stu);
    }
}

运行结果,打印如下:

Student{id=1, name='weihouye2', age=24}

注意sql查询的返回结果一定要是一条数据,否则会抛异常:
没有数据时:

Exception in thread "main" org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
    at org.springframework.dao.support.DataAccessUtils.nullableSingleResult(DataAccessUtils.java:97)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:474)
    at com.shiyanlou.jdbc.App.main(App.java:28)

大于一条数据时:

Exception in thread "main" org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 2
    at org.springframework.dao.support.DataAccessUtils.nullableSingleResult(DataAccessUtils.java:100)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:474)
    at com.shiyanlou.jdbc.App.main(App.java:28)
 6.2、查询多条数据

首先在数据库多添加几条数据:

insert into student values(3,"wangwu",45),(4,"lisi",30);
image.png

修改App.java中的代码,如下:

package com.shiyanlou.jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

/**
 * Hello world!
 *
 */
public class App 
{
    private static ApplicationContext context;
    public static void main( String[] args )
    {
        context = new ClassPathXmlApplicationContext("SpringBeans.xml");

        JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");
//        String sql = "insert into student value(?,?,?)";   //增
//        String sql = "Delete from `student` where id = ?";  //删
//        String sql = "update `student` set name = ? ,age = ? where id = ?"; //改

        String sql = "select * from student";

        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
        List<Student> stus = jt.query(sql,rowMapper);
        for (Student stu:stus
             ) {
            System.out.println(stu);
        }
    }
}

运行查看控制台结果:

Student{id=1, name='weihouye2', age=24}
Student{id=2, name='wei', age=22}
Student{id=3, name='wangwu', age=45}
Student{id=4, name='lisi', age=30}

相关文章

网友评论

      本文标题:Spring JDBC 框架

      本文链接:https://www.haomeiwen.com/subject/dpthbctx.html