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

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

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,密碼123456mysql

 

修改application.yml文件spring

 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.javasql

 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爲app

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

 

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

 

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

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

若是設置成update,若是已經有表不會刪掉原來的表,若是沒有則新建一張表。spring-boot

jpa:
    hibernate:
        ddl-auto: update
        show-sql: true
相關文章
相關標籤/搜索