依赖:
<!--data-jpa的场景启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
常用配置:
# 数据库表的生成策略
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/springdata_jpa?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 是否显示sql在控制台
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.format_sql=true
server.port=8088
可配置项:
jpa.generate-ddl和jpa.hibernate.ddl-auto
jpa.generate-ddl和jpa.hibernate.ddl-auto都可以控制是否执行datasource.schema脚本,来初始化数据库结构,只要有一个为可执行 状态就会执行,比如jpa.generate-ddl:true或jpa.generate-ddl:update,并没有相互制约上下级的关系。 要想不执行,两者都必须是不可执行状态,比如false和none。
采用implicit-strategy和physical-strategy两个配置项分别控制命名策略
naming.implicit-strategy和naming.physical-strategy
spring.jpa.hibernate.naming.implicit‐strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.jpa.hibernate.naming.physical‐strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
(2)、当没有使用@Table和@Column注解时,implicit-strategy配置项才会被使用,当对象模型中已经指定时,implicit-strategy并
不会起作用。
physical-strategy一定会被应用,与对象模型中是否显式地指定列名或者已经被隐式决定无关。 2、implicit-strategy逻辑名称命名策略
有五个配置值: 不会去改:
ImplicitNamingStrategyJpaCompliantImpl:默认的命名策略,兼容JPA 2.0的规范;
ImplicitNamingStrategyLegacyHbmImpl:兼容Hibernate老版本中的命名规范;
ImplicitNamingStrategyLegacyJpaImpl:兼容JPA 1.0规范中的命名规范
ImplicitNamingStrategyComponentPathImpl:大部分与ImplicitNamingStrategyJpaCompliantImpl,但是对于@Embedded等注解标志的 组件处理是通过使用attributePath完成的,
因此如果我们在使用@Embedded注解的时候,如果要指定命名规范,可以直接继承这个类来实现;
默认为ImplicitNamingStrategyJpaCompliantImpl,后四者均继承自它。
3、physical-strategy物理名称命名策略 有两个配置
#直接映射,不会做过多的处理
org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
#表名,字段为小写,当有大写字母的时候会添加下划线分隔符号
org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
默认为SpringPhysicalNamingStrategy
自动配置原理:
通过JpaBaseConfiguration去配置我们以前集成spring data jpa的基本@Bean
JpaRepositoriesAutoConfiguration
@Import(JpaRepositoriesImportSelector.class)
JpaRepositoriesImportSelector又会注册一个ImportBeanDefinitionRegistrar 其实就是JpaRepositoriesRegistrar
‐‐‐‐JpaRepositoriesRegistrar 跟通过@EnableJpaRepositories 导入进来的组件是同一个
就相当于@EnableJpaRepositories