版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Caiaixiong/article/details/86559744
配置文件加载的优先级顺序
- 项目根目录下config文件夹中的配置文件
- 项目根目录下的配置文件
- resources目录下config文件夹中的配置文件
- resources目录下的配置文件
注:相应的.yml后缀文件优先级高于.properties后缀文件
Spring Data JPA配置
相关概念:
- JPA:Java持久化API,定义了对象关系映射以及实体对象持久化的标准接口,比如Hibernate就是一个实现了JPA的ORM框架
- Spring Data JPA基于JPA进一步简化了数据访问层的实现,它提供了一种类似于声明式编程的方式,开发者只需要编写数据访问接口,Spring Data JPA就能基于接口中的方法命名自动生成实现
简单使用Spring Data JPA
例子:定义实体类Book,使用Spring Data JPA自动生成相对应数据表
- 添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- application.yml配置文件
logging:
level:
root: debug
com.cax: debug
file: logs/debug.log
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password:
jpa:
hibernate:
ddl-auto: create
show-sql: true
open-in-view: false
- 实体类Book.java
package com.cax.SpringBootDemo.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String author;
private Integer status;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
- 运行效果
注:在此过程中,可能会遇到两个问题
- 可能会出现“ mysql java.sql.SQLException: The server time zone value‘XXXXXX’”的问题,这是由于数据库和系统时区差异所造成的,需要在数据库链接时,在URL处进行时区设置,即在JDBC连接的url后面加上?serverTimezone=GMT或者是添加?serverTimezone=UTC;
- 由于mysql-connector的版本较高,会出现“Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver.”的问题,这是只需将JDBC的驱动配置修改成com.mysql.cj.jdbc.Driver即可。