zoukankan      html  css  js  c++  java
  • 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);

      }
    }



  • 相关阅读:
    for是个什么玩意
    面向对象 多态
    面向对象 接口
    面向对象oop
    面向对象基本
    java修饰符的作用范围
    static 关键字介绍
    JsonLayout log4j2 json格式输出日志
    多线程--Thread.join方法
    idea常用实用快捷键
  • 原文地址:https://www.cnblogs.com/wxc-xiaohuang/p/9427888.html
Copyright © 2011-2022 走看看