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";  //跳轉成功頁面
    }
}
運行

在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述

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