05.Spring Boot 实战~Spring Boot整合JDBC

05.Spring Boot 实战~Spring Boot整合JDBC

本文是上一篇文章的后续,详情点击该链接

本文用到的数据库表

在这里插入图片描述

【声明:本文数据库内的信息是随机添加用来学习,如有雷同,纯属巧合】

搭建项目框架

在这里插入图片描述

整合JDBC所需要的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.alvin</groupId>
  <artifactId>SpringBootAndJDBC</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBootAndJDBC</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</java.version>
  </properties>


  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

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

    <!--Thymeleaf启动器座标-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!--JDBC启动器座标-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--数据库驱动座标-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.20</version>
    </dependency>

    <!--Druid数据源依赖-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

JDBC配置类

//jdbc的配置类
@Configuration
public class JdbcConfiguration {
    //实例化Druid
    @Bean
    public DataSource getDataSoure(){
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName("com.mysql.cj.jdbc.Driver");
        source.setUrl("jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
        source.setUsername("root");
        source.setPassword("root");
        return source;
    }
}
也可以使用通过扫描properties
//jdbc的配置类
@Configuration
@PropertySource("classpath:/jdbc.properties")//加载指定的Properties配置文件
public class JdbcConfiguration {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    //实例化Druid
    @Bean
    public DataSource getDataSoure(){
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName(driverClassName);
        source.setUrl(url);
        source.setUsername(username);
        source.setPassword(password);
        return source;
    }
}

        这种写法看起来是挺不错的,但是也有一个弊端,那就是写的太死。假如我要在其他类里面需要用到以上定义的四个属性,则又需要重写,代码的复用性不高。那么怎么办呢?我们再来看看另一种方法

        首先还是在刚刚那个包下创建一个JDBCProperties类

@ConfigurationProperties(prefix = "jdbc")
public class JDBCProperties {
    //属性名字必须和配置项后缀一模一样, jdbc.driverClassName
    private String driverClassName;
    private String url;
    private String username;
    private String password;
}//get  set  就不写在文章里面了
修改刚刚的类
//jdbc的配置类
@Configuration
@EnableConfigurationProperties(JDBCProperties.class)    //通过这个注解来指定需要加载的配置属性类
public class JdbcConfiguration {
    @Autowired
    private JDBCProperties jdbcProperties;
    //实例化Druid
    @Bean
    public DataSource getDataSoure(){
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName(this.jdbcProperties.getDriverClassName());
        source.setUrl(this.jdbcProperties.getUrl());
        source.setUsername(this.jdbcProperties.getUsername());
        source.setPassword(this.jdbcProperties.getPassword());
        return source;
    }
}
我们点进@EnableConfigurationProperties源码可以看到

在这里插入图片描述

       它这里返回的是一个Class,所以以后我们如果有多个配置文件,或者有多个需要这个配置文件的类,就不需要每次都重复写代码,直接复用就好了~

最简单的配置类

public class JdbcConfiguration{
/** * 实 例 化 Druid */ 
@Bean 
@ConfigurationProperties(prefix = "jdbc")
 public DataSource getDataSource(){ 
 	DruidDataSource source = new DruidDataSource();
  	return source; 
 }
}

       这样一来我们连实体类都可以不需要了~

通过 SpringBoot 配置文件配置数据源

       在 Spring Boot1.x版本中的spring-boot-starter-jdbc启动器中默认使用的是org.apache.tomcat.jdbc.pool.DataSource 作为数据源

       在 Spring Boot2.x版本中的spring-boot-starter-jdbc启动器中默认使用的是com.zaxxer.hikariDataSource作为数据源

使用 SpringBoot 默认的 HikariDataSource 数据源

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

使用第三方的 Druid 数据源

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

添加学生信息

先创建一个POJO
public class Student implements Serializable{
    private String son;
    private String realname;
    private String password;
    private String classname;
    private Double score;
}//get set就不再文章里面啰嗦了

在这里插入图片描述

编写Insert.html前台页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
    <head>
        <meta charset="UTF-8">
        <title>添加学生</title>
    </head>
    <body>
        <form action="/student/MyControllerInsert" method="post">
            学号: <input type="text" name="son"/><br/>
            姓名: <input type="text" name="realname"/><br/>
            密码: <input type="password" name="password"/><br/>
            院系: <input type="text" name="classname"/><br/>
            成绩: <input type="text" name="score"/><br/>
            <input type="submit" value="提交"/>
        </form>
    </body>
</html>

直接访问时

在这里插入图片描述

现在来看看showPage的作用

编写showPage

@Controller
public class PageController {
    //页面跳转方法
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page){
        return page;
    }
}

在这里插入图片描述

可以直接访问了~

然后我们增加Dao和Service

在这里插入图片描述

Dao层代码

@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //添加用户
    @Override
    public void insertStudent(Student student) {
        String sql = "insert into student values(?,?,?,?,?)";
        this.jdbcTemplate.update(sql,student.getSon(),student.getRealname()
                ,student.getPassword(),student.getClassname(),student.getScore());
    }
}
Service层
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    //添加学生信息
    @Override
    @Transactional  //事务注解
    public void addStudent(Student student) {
        this.studentDao.insertStudent(student);
    }
}
Controller
@Controller
@RequestMapping("/student") //前缀
public class MyController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/MyControllerInsert")
    public String Insert(Student student){
        System.out.println(student);
        try{
            this.studentService.addStudent(student);
        }catch(Exception e){
            e.printStackTrace();
            return"redirect:/error";//跳转失败页面
        }
        return"redirect:/succeed";  //跳转成功页面
    }
}
运行

在这里插入图片描述在这里插入图片描述在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章