[Spring from entry to actual combat tutorial] Chapter 5 Spring JDBC

5. Spring JDBC

    We know that JDBC is an API provided by Java for executing SQL statements, which can access various relational databases (such as MySQL, Oracle, etc.).

    However, in actual enterprise-level application development, few people directly use the native JDBC API for development. This is because it is very cumbersome to use the JDBC API to operate the database, and we need to "control each step step by step, Care everywhere", for example, we need to manually control the opening of database connections, exception handling, transaction processing, and finally manually close connections to release resources and so on.

    Spring provides a Spring JDBC module, which encapsulates the JDBC API. Its main purpose is to reduce the difficulty of using the JDBC API and use the JDBC API in a more direct and concise way.

    Using Spring JDBC, developers only need to define the necessary parameters and specify the SQL statement to be executed, and then they can easily program JDBC and access the database.

    As for the complicated and tedious work of loading the driver, opening and closing the database connection, creating and executing SQL statements, exception handling, and transaction processing, it is all done by Spring JDBC. In this way, developers can be freed from the cumbersome JDBC API and have more energy to focus on business development.

    Spring JDBC provides several practical database access tools to simplify the development of JDBC, among which JdbcTemplate is the most used.

5.1 Introduction to JdbcTemplate

  • JdbcTemplate is the most basic JDBC template in Spring, which encapsulates the method of adding, deleting, modifying and checking data .

  • As the core of the Spring JDBC framework, JDBC templates are designed to provide template methods for different types of JDBC operations. Each template method controls the entire process and allows specific tasks in the process to be overridden. In this way, the workload of database access can be minimized while retaining as much flexibility as possible.

5.2 Development steps

5.2.1 Add the corresponding jar package

Method 1: Import jar package

 Method 2: maven dependency configuration

<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 Database resource files

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 Enable annotations and configure data sources

    Use Spring's built-in data source 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 Configure JdbcTemplate

    Configure the JdbcTemplate, and inject the data source object into the JdbcTemplate.

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

5.2.5 Entity class

Create table 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

interface:

public interface StudentDao {
    void insertStudent(Student student);

    void updateStudent(Student student);

    void deleteStudent(Integer id);

    Student selectStudentById(Integer id);

    List<Student> selectStudent();
}

Implementation class: JdbcTemplate is used as a member variable of Dao, and CURD operation is realized through JdbcTemplate

@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 Testing

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);
        }
    }
}

Guess you like

Origin blog.csdn.net/ligonglanyuan/article/details/124809717