【Spring从入门到实战教程】第五章 Spring JDBC

五、Spring JDBC

    我们知道,JDBC 是 Java 提供的一种用于执行 SQL 语句的 API,可以对多种关系型数据库(例如 MySQL、Oracle 等)进行访问。

    但在实际的企业级应用开发中,却很少有人直接使用原生的 JDBC API 进行开发,这是因为使用 JDBC API 对数据库进行操作十分繁琐,需要我们对每一步都做到“步步把控,处处关心”,例如我们需要手动控制数据库连接的开启,异常处理、事务处理、最后还要手动关闭连接释放资源等等。

    Spring 提供了一个 Spring JDBC 模块,它对 JDBC API 进行了封装,其的主要目的降低 JDBC API 的使用难度,以一种更直接、更简洁的方式使用 JDBC API。

    使用 Spring JDBC,开发人员只需要定义必要的参数、指定需要执行的 SQL 语句,即可轻松的进行 JDBC 编程,对数据库进行访问。

    至于驱动的加载、数据库连接的开启与关闭、SQL 语句的创建与执行、异常处理以及事务处理等繁杂乏味的工作,则都是由 Spring JDBC 完成的。这样就可以使开发人员从繁琐的 JDBC API 中解脱出来,有更多的精力专注于业务的开发。

    Spring JDBC 提供了多个实用的数据库访问工具,以简化 JDBC 的开发,其中使用最多就是 JdbcTemplate。

5.1 JdbcTemplate简介

  • JdbcTemplate是Spring里面最基本的JDBC模板,其中封装了对数据的增删改查的方法

  • 作为Spring JDBC框架的核心,JDBC模板的设计目的是为不同类型的JDBC操作提供模板方法。每个模板方法都能控制整个过程,并允许覆盖过程中的特定任务。通过这种方式,可以在尽可能保留灵活性的情况下,将数据库存取的工作量降到最低。

5.2 开发步骤

5.2.1 加入相应的jar包

方式一:引入jar包

 方式二:maven依赖配置

<dependencies>
    <!-- spring核心包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springbean包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springcontext包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- spring表达式包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springAOP包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springAspects包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springJDBC包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- spring事务包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.49</version>
    </dependency>
    <!-- oracle驱动 -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

5.2.2 数据库资源文件

db.properties:

# Oracle相关配置
jdbc.oracle.driver=oracle.jdbc.driver.OracleDriver
jdbc.oracle.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.oracle.username=scott
jdbc.oracle.password=tiger

# Mysql相关配置
jdbc.mysql.driver=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8&useSSL=false
jdbc.mysql.username=root
jdbc.mysql.password=root

5.2.3 开启注解和配置数据源

    采用Spring内置的数据源org.springframework.jdbc.datasource.DriverManagerDataSource

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:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    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/util
    http://www.springframework.org/schema/util/spring-util.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">
	
    <!--开启注解:组件扫描-->
    <context:component-scan base-package="com.newcapec"/>
    
    <!-- 读取资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 连接数据库的基础信息 -->
        <property name="driverClassName" value="${jdbc.mysql.driver}"/>
        <property name="url" value="${jdbc.mysql.url}"/>
        <property name="username" value="${jdbc.mysql.username}"/>
        <property name="password" value="${jdbc.mysql.password}"/>
    </bean>
</beans>

5.2.4 配置JdbcTemplate

    配置JdbcTemplate,并且将数据源对象注入到JdbcTemplate中。

<!-- 配置JDBCTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!-- 将连接数据库时使用的数据源对象,注入到JDBCTemplate对象中 -->
    <property name="dataSource" ref="dataSource"/>
</bean>

5.2.5 实体类

建表SQL:

CREATE TABLE T_STUDENT(
  id    INT PRIMARY KEY AUTO_INCREMENT,
  name  VARCHAR(20),
  age   INT(3),
  major VARCHAR(50)
);

insert into T_STUDENT (id, name, age, major) values (1, '小明', 22, '软件工程');
insert into T_STUDENT (id, name, age, major) values (2, '小张', 20, '计算机科学与技术');
insert into T_STUDENT (id, name, age, major) values (3, '小刘', 21, '信息安全');

Student.java:

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private String major;

    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 Integer getAge() {
        return age;
    }

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

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

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

5.2.6 Dao

接口:

public interface StudentDao {
    void insertStudent(Student student);

    void updateStudent(Student student);

    void deleteStudent(Integer id);

    Student selectStudentById(Integer id);

    List<Student> selectStudent();
}

实现类:JdbcTemplate作为Dao的成员变量,通过JdbcTemplate实现CURD操作

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insertStudent(Student student) {
        /**
         * update(String sql, Object... args)
         * sql : sql语句
         * args : Object...动态参数,表示参数的个数不限,传入sql语句中的占位符的数据
         *
         * 返回值为影响数据库表的条数
         *
         * 注意:占位符数据的顺序必须与sql语句中占位符的顺序保持一致
         */
        String sql = "insert into t_student(name,age,major) values(?,?,?)";
        int i = jdbcTemplate.update(sql, student.getName(), student.getAge(), student.getMajor());
        System.out.println("新增成功,影响条数为:" + i);
    }

    @Override
    public void updateStudent(Student student) {
        String sql = "update t_student set name=?,age=?,major=? where id=?";
        jdbcTemplate.update(sql, student.getName(), student.getAge(), student.getMajor(), student.getId());
    }

    @Override
    public void deleteStudent(Integer id) {
        String sql = "delete from t_student where id=?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public Student selectStudentById(Integer id) {
        String sql = "select id,name,age,major from t_student where id=?";
        /**
         * RowMapper行映射器
         * 作用:将sql语句中数据映射到实体对象中
         * BeanPropertyRowMapper是RowMapper的实现,使用它来实现基本数据的映射
         * 要求:结果集中的字段名称与实体类中属性名称保持一致
         */
        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);

        Student student = jdbcTemplate.queryForObject(sql, rowMapper, id);
        return student;
    }

    @Override
    public List<Student> selectStudent() {
        String sql = "select id,name,age,major from t_student order by id desc";
        /**
         * queryForList(sql)
         * 返回值为List<Map<String,Object>>
         * 其中Map集合中存放就是每一行中的数据,键为字段名称,值为字段对应的数据值
         */
        /*List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : list1) {
            System.out.println(map);
        }*/
        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
        List<Student> list = jdbcTemplate.query(sql, rowMapper);
        return list;
    }
}

5.2.7 测试

public class SpringJdbcTest {
    @Test
    public void testDataSource() throws SQLException {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource ds = ac.getBean("dataSource", DataSource.class);
        System.out.println(ds);
    }

    @Test
    public void testInsert() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentDao studentDao = ac.getBean("studentDao", StudentDao.class);
        Student student = new Student();
        student.setName("小李");
        student.setAge(20);
        student.setMajor("通信工程");
        studentDao.insertStudent(student);
    }

    @Test
    public void testUpdate() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentDao studentDao = ac.getBean("studentDao", StudentDao.class);
        Student student = new Student();
        student.setId(4);
        student.setName("大刘");
        student.setAge(24);
        student.setMajor("信息管理");
        studentDao.updateStudent(student);
    }

    @Test
    public void testDelete() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentDao studentDao = ac.getBean("studentDao", StudentDao.class);
        studentDao.deleteStudent(4);
    }

    @Test
    public void testSelectById() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentDao studentDao = ac.getBean("studentDao", StudentDao.class);
        Student student = studentDao.selectStudentById(1);
        System.out.println(student);
    }

    @Test
    public void testSelect() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentDao studentDao = ac.getBean("studentDao", StudentDao.class);
        List<Student> list = studentDao.selectStudent();
        for (Student student : list) {
            System.out.println(student);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ligonglanyuan/article/details/124809717
今日推荐