> 文档中心 > 【Spring从入门到实战教程】第五章 Spring JDBC

【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依赖配置

         org.springframework spring-core 4.3.18.RELEASE             org.springframework spring-beans 4.3.18.RELEASE             org.springframework spring-context 4.3.18.RELEASE             org.springframework spring-expression 4.3.18.RELEASE             org.springframework spring-aop 4.3.18.RELEASE             org.springframework spring-aspects 4.3.18.RELEASE             org.springframework spring-jdbc 4.3.18.RELEASE             org.springframework spring-tx 4.3.18.RELEASE             mysql mysql-connector-java 5.1.49             com.oracle ojdbc6 11.2.0         junit junit 4.12 test    

5.2.2 数据库资源文件

db.properties:

# Oracle相关配置jdbc.oracle.driver=oracle.jdbc.driver.OracleDriverjdbc.oracle.url=jdbc:oracle:thin:@localhost:1521:orcljdbc.oracle.username=scottjdbc.oracle.password=tiger# Mysql相关配置jdbc.mysql.driver=com.mysql.jdbc.Driverjdbc.mysql.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8&useSSL=falsejdbc.mysql.username=rootjdbc.mysql.password=root

5.2.3 开启注解和配置数据源

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

applicationContext.xml:

                              

5.2.4 配置JdbcTemplate

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

        

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