1. 程式人生 > 實用技巧 >springboot學習2(連線mysql資料庫)

springboot學習2(連線mysql資料庫)

1、新增對應依賴

 1     <!--jpa依賴-->
 2         <dependency>
 3             <groupId>org.springframework.boot</groupId>
 4             <artifactId>spring-boot-starter-data-jpa</artifactId>
 5         </dependency>
 6 <!--mysql資料庫驅動程式-->
 7         <dependency>
 8
<groupId>mysql</groupId> 9 <artifactId>mysql-connector-java</artifactId> 10 </dependency> 11 </dependencies>

2、在application.properties中新增資料庫連線配置配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username
=root spring.datasource.password=root
#每次執行程式,沒有表格會新建表格,表內有資料不會清空,只會更新
#每次執行程式,沒有表格會新建表格,表內資料不會清空,只會更新
spring.jpa.hibernate.ddl
-auto=update

ddl-auto:create----每次執行該程式,沒有表格會新建表格,表內有資料會清空

ddl-auto:create-drop----每次程式結束的時候會清空表

ddl-auto:update----每次執行程式,沒有表格會新建表格,表內有資料不會清空,只會更新

ddl-auto:validate----執行程式會校驗資料與資料庫的欄位型別是否相同,不同會報錯

.properties 中採用【.】來配置層級關係 如:spring.datasource.url,

而yml配置檔案中 則使用換行縮排來配置層級關係,如:

spring:
  datasource:
    url:

上述配置完成後,啟動報錯:the server time zone value '�й���׼ʱ��' isunrecognized

在將spring.datasource.url改為如下配置後啟動成功

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8

3、在啟動程式統計資料夾下新建java類

@Entity
public class Family {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
}

之後重新啟動程式,資料庫中將會出現一個family表。