Spring Boot整合JdbcTemplate访问数据库

这篇文章是介绍 Spring Boot整合JdbcTemplate,配置数据源来访问数据库。

在pom文件里添加 spring-boot-starter-jdbc 和mysql依赖。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.21</version>
</dependency>

配置数据源 :在 src/main/resources/application.properties 中配置数据源信息
```
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_demo
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```

建表:
```
DROP TABLE IF EXISTS Student;

CREATE TABLE Student (
  id int(5) NOT NULL,
  name varchar(60) NOT NULL,
  age int(2) NOT NULL,
  score double(5,2) NOT NULL,
  PRIMARY KEY (id)
) ;

启动类:

package cn.yideng;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableAutoConfiguration
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

实体类:

public class Student {

  private int id;
  private String name;
  private int age;
  private double score;

  public Student() {}

  public Student(int id, String name, int age, double score) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.score = score;
  }

// 省略 getter/setter, toString
}

service:

public interface StudentService {

  // 新增
  void create(Student student);

  // 查询所有记录
  List<Student> getAll();

  // 删除所有
  void deleteAllUsers();

  // 根据id修改
  void updateById(Student s);

  // 根据ID查询
  Student getOneById(int id);

}

service实现类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service(value="studentService")
public class StudentServiceImpl implements StudentService{

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Override
  public void create(Student s) {
    String sql = "insert into STUDENT(ID, NAME, AGE, score) values(?, ?, ?, ?)";
    jdbcTemplate.update(sql, s.getId(), s.getName(), s.getAge(), s.getScore());
  }

  @Override
  public List<Student> getAll() {
    String sql = "select * from STUDENT ";
    return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Student.class));
  }

  @Override
    public void deleteAllUsers() {
    String sql = "delete from STUDENT";
    jdbcTemplate.execute(sql);
  }

  @Override
  public void updateById(Student s) {
    String sql = "update STUDENT set name=?, age=?, score=? where id=?";
    jdbcTemplate.update(sql, new Object[]{s.getName(), s.getAge(), s.getScore(), s.getId()});
  }

  @Override
  public Student getOneById(int id) {
    String sql = "select * from STUDENT where id = ?";
    return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Student.class));
  }

}

使用JUnit测试,在pom文件里先添加依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

写测试类,

import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=DemoApplication.class)
@WebAppConfiguration
public class JdbcTest {

  @Autowired
  private StudentService studentService;

  @Test
  public void test() throws Exception {

  // 先删除所有数据
  studentService.deleteAllUsers();

  Student s1 = new Student(1001, "andy lau", 11, 80.00);
  Student s2 = new Student(1002, "lucy 1", 12, 85.00);
  Student s3 = new Student(1003, "lily", 13, 75.00);
  Student s4 = new Student(1004, "tom kk", 14, 94.00);
  studentService.create(s1);
  studentService.create(s2);
  studentService.create(s3);
  studentService.create(s4);

  // 查询所有
  List<Student> stuList = studentService.getAll();
  for(Student stu : stuList){
    System.out.println(stu);
  }

  // 根据ID查询
  Student stu = studentService.getOneById(1003);
  System.out.println("---update 前----" + stu);
  stu.setName("lily Green");
  stu.setScore(90.00);
  // 根据id修改
  studentService.updateById(stu);
  System.out.println("---update 后----" + stu);

  }
}

原文地址:https://www.cnblogs.com/wxc-xiaohuang/p/9427888.html

时间: 2024-08-06 00:51:32

Spring Boot整合JdbcTemplate访问数据库的相关文章

Spring Boot 整合JDBCTemplate

1. 首先配置pom.xml 1.1 dbcm2 是数据源类型,表示配置dataSource的方式 1.2 spring-boot-starter-jdbc是表示让spring boot 支持jdbc 1.3 加入对oracle支持的jar包. 2. 创建配置文件,定义你的数据库连接池,在src/main.resources下面创建application.properties文件. 加入你的数据库配置,如下: spring.datasource.username=xxxxx spring.dat

spring boot与jdbcTemplate的整合案例2

简单入门了spring boot后,接下来写写跟数据库打交道的案例.博文采用spring的jdbcTemplate工具类与数据库打交道. 下面是搭建的springbootJDBC的项目的总体架构图: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www

使用Spring的JdbcTemplate访问数据库 转

使用Spring的JdbcTemplate访问数据库 JdbcTemplate 模板可以简化JDBC操作,但是创建一个JdbcTemplate需要一个DataSource接口,在Spring中,当然就是向 JdbcTemplate中注入一个DataSource,然后通过JdbcTemplate来获取一个连接(Connection). 假设SQL Server 2000数据库(新建的数据库名称为hibernate)中有一张person表,简单地记录了人员的详细信息. 使用Spring的IOC机制实

Spring Boot 整合JDBC 实现后端项目开发

一.前言 前后端分离开发是将项目开发工作前后端交互工作拆分,使前端开发人员能够专注于页面开发或APP 开发,后端开发人员专注与接口开发.业务逻辑开发. 此处开发后端项目,给前端或者APP 端提供接口.不涉及复杂的业务逻辑,通过简单的增删改查来演示后端开发项目. 环境介绍: 开发工具:IDEA JDK: 1.7 及以上 Spring Boot: 2.0 及以上 Maven: 3.0 及以上 二.新建Spring Boot 项目 通过功能菜单File - New - Project 新建Spring

spring boot 与 JdbcTemplate 一起工作

spring boot 与 JdbcTemplate 一起工作 本文将介绍如何将spring boot 与 JdbcTemplate一起工作. Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中. JdbcTemplate 是在JDBC API基础上提供了更抽象的封装,并提供了基于方法注解的事务管理能力. 通过使用SpringBoot自动配置功能并代替我们自动配置beans. 在maven中,我们需要

企业分布式微服务云SpringCloud SpringBoot mybatis (十三)Spring Boot整合MyBatis

Spring中整合MyBatis就不多说了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步骤.搜了一下Spring Boot整合MyBatis的文章,方法都比较老,比较繁琐.查了一下文档,实际已经支持较为简单的整合与使用.下面就来详细介绍如何在Spring Boot中整合MyBatis,并通过注解方式实现映射. 整合MyBatis 新建Spring Boot项目,或以Chapter1为基础来操作 pom.xml中引入依赖 这里用到spring-bo

Spring Boot整合Elasticsearch

Spring Boot整合Elasticsearch Elasticsearch是一个全文搜索引擎,专门用于处理大型数据集.根据描述,自然而然使用它来存储和搜索应用程序日志.与Logstash和Kibana一起,它是强大的解决方案Elastic Stack的一部分,我之前的一些文章中已经对此进行了描述. 保留应用程序日志不是Elasticsearch的唯一使用场景.它通常用作应用程序的辅助数据库,是一个主关系数据库.如果您必须对大型数据集执行全文搜索或仅存储应用程序不再修改的许多历史记录,这个方

Spring Boot 整合 JPA 使用多个数据源

介绍# JPA(Java Persistence API)Java 持久化 API,是 Java 持久化的标准规范,Hibernate 是持久化规范的技术实现,而 Spring Data JPA 是在 Hibernate 基础上封装的一款框架.第一次使用 Spring JPA 的时候,感觉这东西简直就是神器,几乎不需要写什么关于数据库访问的代码一个基本的 CURD 的功能就出来了.在这篇文章中,我们将介绍 Spring Boot 整合 JPA 使用多个数据源的方法.开发环境: Spring Bo

spring boot 整合 quartz 集群环境 实现 动态定时任务配置【原】

最近做了一个spring boot 整合 quartz  实现 动态定时任务配置,在集群环境下运行的 任务.能够对定时任务,动态的进行增删改查,界面效果图如下: 1. 在项目中引入jar 2. 将需要的表导入数据库 官网上有不同数据库的脚本,找到对应的,导入即可 3. java 代码 将quartz 的相关配置文件,配置为暴露bean,方便后期引用. 有一处关键的地方,就是注入spring 上下文,也可以算是一个坑.如果,不注入spring 上下文,那么新添加的定时任务job,是新new 的一个