[Primavera desde la entrada al tutorial de combate real] Capítulo 5 Primavera JDBC

5. Primavera JDBC

    Sabemos que JDBC es una API provista por Java para ejecutar sentencias SQL, que pueden acceder a varias bases de datos relacionales (como MySQL, Oracle, etc.).

    Sin embargo, en el desarrollo de aplicaciones de nivel empresarial real, pocas personas usan directamente la API nativa de JDBC para el desarrollo.Esto se debe a que usar la API de JDBC para operar la base de datos es muy engorroso y requiere que "controlemos cada paso, cuidado en todas partes", por ejemplo. , necesitamos controlar manualmente la apertura de las conexiones de la base de datos, el manejo de excepciones, el procesamiento de transacciones y, finalmente, cerrar manualmente las conexiones para liberar recursos, etc.

    Spring proporciona un módulo Spring JDBC, que encapsula la API de JDBC. Su propósito principal es reducir la dificultad de usar la API de JDBC y usar la API de JDBC de una manera más directa y concisa.

    Usando Spring JDBC, los desarrolladores solo necesitan definir los parámetros necesarios y especificar la instrucción SQL que se ejecutará, y luego pueden programar JDBC fácilmente y acceder a la base de datos.

    En cuanto al trabajo complicado y tedioso de cargar el controlador, abrir y cerrar la conexión de la base de datos, crear y ejecutar declaraciones SQL, manejo de excepciones y procesamiento de transacciones, todo lo realiza Spring JDBC. De esta forma, los desarrolladores pueden liberarse de la engorrosa API de JDBC y tener más energía para concentrarse en el desarrollo empresarial.

    Spring JDBC proporciona varias herramientas prácticas de acceso a bases de datos para simplificar el desarrollo de JDBC, entre las cuales JdbcTemplate es la más utilizada.

5.1 Introducción a JdbcTemplate

  • JdbcTemplate es la plantilla JDBC más básica en Spring, que encapsula el método de agregar, eliminar, modificar y verificar datos .

  • Como núcleo del marco Spring JDBC, las plantillas JDBC están diseñadas para proporcionar métodos de plantilla para diferentes tipos de operaciones JDBC. Cada método de plantilla controla todo el proceso y permite anular tareas específicas del proceso. De esta forma, la carga de trabajo del acceso a la base de datos se puede minimizar manteniendo la mayor flexibilidad posible.

5.2 Pasos de desarrollo

5.2.1 Agregar el paquete jar correspondiente

Método 1: Importar paquete jar

 Método 2: configuración de dependencia 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 Archivos de recursos de la base de datos

db.propiedades:

# 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 Habilitar anotaciones y configurar fuentes de datos

    Utilice la fuente de datos integrada de Spring org.springframework.jdbc.datasource.DriverManagerDataSource

contexto de aplicación.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 Configurar plantilla Jdbc

    Configure JdbcTemplate e inyecte el objeto de origen de datos en JdbcTemplate.

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

5.2.5 Clase de entidad

Crear tabla 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, '信息安全');

Estudiante.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 Tao

interfaz:

public interface StudentDao {
    void insertStudent(Student student);

    void updateStudent(Student student);

    void deleteStudent(Integer id);

    Student selectStudentById(Integer id);

    List<Student> selectStudent();
}

Clase de implementación: JdbcTemplate se usa como una variable miembro de Dao, y la operación CURD se realiza a través de 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 Pruebas

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

Supongo que te gusta

Origin blog.csdn.net/ligonglanyuan/article/details/124809717
Recomendado
Clasificación