Java框架spring Boot學習筆記(四):Spring Boot操作MySQL數據庫


在pom.xml添加一下代碼,添加操作MySQL的依賴jar包。

1 <dependency>
2   <groupId>org.springframework.boot</groupId>
3   <artifactId>spring-boot-starter-data-jpa</artifactId>
4 </dependency>
5 
6 <dependency>
7   <groupId>mysql</groupId>
8   <artifactId>mysql-connector-java</artifactId>
9 </dependency>

 

新建dbpeople的一個數據庫,用戶名root,密碼123456

 

修改application.yml文件

 1 spring:
 2   profiles:
 3     active: prod
 4   datasource:
 5     driver-class-name: com.mysql.jdbc.Driver
 6     url: jdbc:mysql://localhost:3306/dbpeople
 7     username: root
 8     password: 123456
 9   jpa:
10     hibernate:
11       ddl-auto: create #update
12     show-sql: true

 

添加一個people類People.java

 1 package com.example.demo;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.GeneratedValue;
 5 import javax.persistence.Id;
 6 
 7 //@Entity對應數據庫中的一個表
 8 @Entity
 9 public class People {
10 
11     //@Id配合@GeneratedValue,表示id自增長
12     @Id
13     @GeneratedValue
14     private Integer id;
15     private String name;
16     private Integer age;
17 
18     //必須要有一個無參的構造函數,不然數據庫會報錯
19     public People() {
20     }
21 
22     public Integer getId() {
23         return id;
24     }
25 
26     public void setId(Integer id) {
27         this.id = id;
28     }
29 
30     public String getName() {
31         return name;
32     }
33 
34     public void setName(String name) {
35         this.name = name;
36     }
37 
38     public Integer getAge() {
39         return age;
40     }
41 
42     public void setAge(Integer age) {
43         this.age = age;
44     }
45 }

 

運行報錯:

Thu Nov 16 10:29:29 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

是因為高版本的MySQL連接需要useSSL=true,在application.yml文件中修改MySQL連接的url為

url: jdbc:mysql://localhost:3306/dbpeople?useSSL=true

 

運行成功刷新數據庫發現生成了一個people的表

 

在application.yml中的ddl-auto設置為create表示每次運行都會刪掉以前的表,再建一張新表

jpa:
    hibernate:
        ddl-auto: create 
        show-sql: true        

如果設置成update,如果已經有表不會刪掉原來的表,如果沒有則新建一張表。

jpa:
    hibernate:
        ddl-auto: update
        show-sql: true

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM