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
相关文章
相关标签/搜索