Spring框架+jdbcTemplate实现增删改查功能

SpringMVC架构(Model(实体类),Service,Controller层)

Controller(接收参数调用业务层)–>Service(调用持久层,处理业务逻辑)–>Dao(与数据库交互)

1. IOC(控制反转是一种设计思想而不是技术)

DI(依赖注入):是IOC思想的一种技术实现

IOC容器是Spring提供的保存Bean对象的容器

Bean管理操作

1.Xml + 注解

2.javaConfig + 注解

通过xml配置Bean:TODO:

通过javaConfig 配置Bean:TODO:

通过注解配置Bean:TODO:

2. AOP(面向切面)

面向切面的程序设计思想。横向的调用。

eg:一个日志的功能,很多的功能模块都需要去使用,可以写一个切面去做这个事情。

使用@Aspect来标记一个普通类为切面。

连接点:比如说日志需要作用的方法。

目标对象:日志需要使用的对象。

1. 添加依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7</version>
    <scope>runtime</scope>
</dependency>

2.demo练习

需求:SpringIOC + JDBCTemplate实现简单的数据库操作

1.新建Maven项目并引入Spring核心4依赖

<!--Spring的4个基础jar包(容器包)-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.3.1</version>
        </dependency>

jdbc依赖

<!--Spring整合jdbc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.6</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

junit5

<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.2</version>
            <scope>test</scope>
        </dependency>

2. 创建SpringConfig配置文件(通过JavaConfig方式注入bean)

创建SpringConfig类,添加@Configuration标记为配置类。

配置数据源和JDBCTemplateBean

/**
 * @author YonC
 * @date 2021/9/2
 */
@Configuration
public class SpringConfig {
    @Bean
    public DataSource dataSource() {
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=ture&charactorEncoding=utf-8&serverTimezone=UTC");
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

3.创建MVC架构并创建与数据库字段对应的实体类对象

实体类:StudentPO

public class StudentPO {
    private Long id;
    private String name;
    private String age;

    public StudentPO() {
    }

    public StudentPO(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public StudentPO(Long id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

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

4. 编写Dao层

面向接口编程,首先定义Dao层的规范接口,定义了增删改查4种方法

/**
 * @author YonC
 * @date 2021/9/2
 */
public interface StudentDao {
    void addStudent(StudentPO student);

    void delStudentById(Long id);

    void updateStudent(StudentPO student);

    List<StudentPO> selectStudent();
}

接口的实现

@Repository注解将StudentDao注入IOC容器

@Autowired自动装配JdbcTemplate对象,JdbcTemplate对象已经在SpringConfig文件中实例化

/**
 * @author YonC
 * @date 2021/9/2
 */
@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    /*
     * 增加Student
     * */
    @Override
    public void addStudent(StudentPO student) {
        jdbcTemplate.update("insert into student (name,age) values (?,?)", student.getName(), student.getAge());
    }

    /*
     * 删除Student
     * */
    @Override
    public void delStudentById(Long id) {
        jdbcTemplate.update("delete from student where id=?", id);
    }

    /*
     * 修改Student
     * */
    @Override
    public void updateStudent(StudentPO student) {
        String sql = "UPDATE student SET name=?,age=? where id = ? ";
        Object[] args = {student.getName(), student.getAge(), student.getId()};
        jdbcTemplate.update(sql, args);
    }

    /*
     * 查询
     * */
    @Override
    public List<StudentPO> selectStudent() {
        String sql = "select id,name,age from student";
        return this.jdbcTemplate.query(sql, (rs, index) -> {
            StudentPO student = new StudentPO();
            student.setId(rs.getLong("id"));
            student.setName(rs.getString("name"));
            student.setAge(rs.getString("age"));
            return student;
        });
    }
}

5. Dao与数据库的增删改查已经实现,使用Service层去调用Dao层的方法。

首先定义Service层的接口

/**
 * @author YonC
 * @date 2021/9/2
 */
public interface StudentService {

    void addStudent(StudentPO student);

    void delStudentById(Long id);

    void updateStudent(StudentPO student);

    List<StudentPO> selectStudent();
}

接口实现

@Service将对象声明IOC容器中

@Autowired自动装配IOC容器中的StudentDaoStudentDao对象初始化

/**
 * @author YonC
 * @date 2021/9/2
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentDao studentDao;

    @Override
    public void addStudent(StudentPO student) {
        studentDao.addStudent(student);
    }

    @Override
    public void delStudentById(Long id) {
       studentDao.delStudentById(id);
    }

    @Override
    public void updateStudent(StudentPO student) {
       studentDao.updateStudent(student);
    }

    @Override
    public List<StudentPO> selectStudent() {
        return studentDao.selectStudent();
    }
}

6. 使用Junit5单元测试测试

首先通过IOC容器拿到StudentService对象

private AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    // 通过Spring的IOC容器
    private StudentService studentService = applicationContext.getBean(StudentService.class);

测试

/**
 * @author YonC
 * @date 2021/9/2
 */
class StudentServiceImplTest {

    private AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    // 通过Spring的IOC容器
    private StudentService studentService = applicationContext.getBean(StudentService.class);
    @Test
    public void testAddStudent() {

        studentService.addStudent(new StudentPO("zahngsna", "999"));
        System.out.println("添加成功!");
    }

    @Test
    public void testDelStudent() {
        studentService.delStudentById(3L);
        System.out.println("删除成功!");
    }

    @Test
    public void testUpdateStudent() {
        //将id为3的Student的name修改为"wang",age修改为21
        studentService.updateStudent(new StudentPO(1L,"wang","28"));
        System.out.println("修改成功!");
    }

    @Test
    public void testSelectStudent() {
        studentService.selectStudent().forEach(System.out::println);
    }

}

到此这篇关于Spring框架+jdbcTemplate实现增删改查功能的文章就介绍到这了,更多相关Spring jdbcTemplate增删改查内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot使用JdbcTemplate操作数据库

    前言 本文是对SpringBoot使用JdbcTemplate操作数据库的一个介绍,提供一个小的Demo供大家参考. 操作数据库的方式有很多,本文介绍使用SpringBoot结合JdbcTemplate. 新建项目 新建一个项目.pom文件中加入Jdbc依赖,完整pom如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM

  • springboot使用JdbcTemplate完成对数据库的增删改查功能

    首先新建一个简单的数据表,通过操作这个数据表来进行演示 DROP TABLE IF EXISTS `items`; CREATE TABLE `items` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `name` varchar(10) DEFAULT NULL, `detail` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE

  • SpringBoot JdbcTemplate批量操作的示例代码

    前言 在我们做后端服务Dao层开发,特别是大数据批量插入的时候,这时候普通的ORM框架(Mybatis.hibernate.JPA)就无法满足程序对性能的要求了.当然我们又不可能使用原生的JDBC进行操作,那样尽管效率会高,但是复杂度会上升. 综合考虑我们使用Spring中的JdbcTemplate和具名参数namedParameterJdbcTemplate来进行批量操作. 改造前 在开始讲解之前,我们首先来看下之前的JPA是如何批量操作的. 实体类User: public class App

  • Spring框架+jdbcTemplate实现增删改查功能

    SpringMVC架构(Model(实体类),Service,Controller层) Controller(接收参数调用业务层)–>Service(调用持久层,处理业务逻辑)–>Dao(与数据库交互) 1. IOC(控制反转是一种设计思想而不是技术) DI(依赖注入):是IOC思想的一种技术实现 IOC容器是Spring提供的保存Bean对象的容器 Bean管理操作 1.Xml + 注解 2.javaConfig + 注解 通过xml配置Bean:TODO: 通过javaConfig 配置B

  • Java中SSM框架实现增删改查功能代码详解

    记录一下自己第一次整合smm框架的步骤. 参考博客和网站有:我没有三颗心脏 How2J学习网站 1.数据库使用的是mySql,首先创建数据库ssm1,并创建表student create database ssm1; use ssm1; CREATE TABLE student( id int(11) NOT NULL AUTO_INCREMENT, student_id int(11) NOT NULL UNIQUE, name varchar(255) NOT NULL, age int(1

  • Spring boot+mybatis+thymeleaf 实现登录注册增删改查功能的示例代码

    本文重在实现理解,过滤器,业务,逻辑需求,样式请无视.. 项目结构如下 1.idea新建Spring boot项目,在pom中加上thymeleaf和mybatis支持.pom.xml代码如下 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3

  • 使用Spring Data R2DBC +Postgres实现增删改查功能

    在本教程中,我想向您展示如何通过带有Spring WebFlux的Spring Data R2DBC 执行各种Postgres CRUD操作. R2DBC代表反应式关系数据库连接. 像JPA(Java持久性API)一样,R2DBC是关系数据库的反应性驱动程序的规范.由于它是一个单独的规范,因此请勿与JPA / Hibernate功能(如@OneToMany,@ManyToMany 等)比较. 我们将开发一个名为product-service的Spring Boot应用程序,该应用程序负责创建新产

  • 使用SpringBoot开发Restful服务实现增删改查功能

    在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练.不过在看了很多关于SpringBoot的介绍之后,并没有想象中的那么难,于是开始准备学习SpringBoot. 在闲暇之余的时候,看了下SpringBoot实战以及一些大神关于SpringBoot的博客之后,开始写起了我的第一个SpringBoot的项目.在能够对SpringBoot进行一些简单的开发Re

  • Mybatis开发环境搭建实现数据的增删改查功能

    config.xml的配置 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 拿到数据库

  • BootstrapTable与KnockoutJS相结合实现增删改查功能【二】

    在上篇文章给大家介绍了BootstrapTable与KnockoutJS相结合实现增删改查功能[一],介绍了下knockout.js的一些基础用法.接下来通过本文继续给大家介绍.如果你也打算用ko去做项目,且看看吧! Bootstrap是一个前端框架,解放Web开发者的好东东,展现出的UI非常高端大气上档次,理论上可以不用写一行css.只要在标签中加上合适的属性即可. KnockoutJS是一个JavaScript实现的MVVM框架.非常棒.比如列表数据项增减后,不需要重新刷新整个控件片段或自己

  • BootstrapTable与KnockoutJS相结合实现增删改查功能【一】

    Bootstrap是一个前端框架,解放Web开发者的好东东,展现出的UI非常高端大气上档次,理论上可以不用写一行css.只要在标签中加上合适的属性即可. KnockoutJS是一个JavaScript实现的MVVM框架.非常棒.比如列表数据项增减后,不需要重新刷新整个控件片段或自己写JS增删节点,只要预先定义模板和符合其语法定义的属性即可.简单的说,我们只需要关注数据的存取. 一.Knockout.js简介 1.Knockout.js和MVVM 如今,各种前端框架应接不暇,令人眼花缭乱,有时不得

  • JS结合bootstrap实现基本的增删改查功能

    提出问题:如何利用原生的js实现基本的增删改查功能??? 解决问题 假如你已经对JS有一定基础 假如你对bootstrap有一定基础 下面是具体的例子, 包含两个文件(index.jsp  和  index.js) <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC

随机推荐