spring boot使用JPA和配置

1认识JPA

JPA (Java Pesitence API )是 Java 的持久化 API ,用于对象的持久化。它是一个非常强 大的 ORM 持久化的解决方案 免去了使用 JDBCTemplate 开发的编写脚本工作。 JPA 通过简单约定好接口方法的规则自动生成相应的 JPQL 语句,然后映射成 POJO 对象

JPA 是一个规范化接口,封装了 Hibernate 的操作作为默认实现 让用户不通过任何配置即可完成数据库的操作。 JPA Spring Date 相同bernate 的关系如图 所示
在这里插入图片描述

Hibernate 主要通过 hibernate-annotation,hibernate -entitymanage 相同hibernate-core三个组件来操作数据。

• hibernate-annotation :是 Hibernate 支持 annotation 万式配 的基础,它包括标准的 JPA annotation, Hibernate 自身特殊功能的 annotation

• hibernate-core :是 Hibernate 的核心实现,提供了 Hibernate 所有的核心功能

• hibernate-entitymanager:实现了标准的 JPA ,它是 hibernate core和 JPA 之间的适 配器,它不直接提供 ORM 的功能,而是对 hibernate-core 进行封装,使得 Hibernate 符合JPA 的规范

每次加载 Hibernate 时会根据 Model 类生成表,但是 sessionFactotory 旦关闭 表就会自动被删除

2.spring boot配置使用JPA

以mysql为例

		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
	 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>

2配置数据库连接信息

Spring Boot 项目使用 MySQ 等关系型数据库,需要配置连接信患, 可以在 application.properties 或者application.yml文件中进行配置。以下代码配置了与 MySQL 数据库的连接信患:

properties形式

spring.datasource.url=jdbc:mysql//127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTi
mezone=UTC&useSSL =true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true

yml形式

spring:
  datasource:
    url: jdbc:mysql//127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL =true
    data-username: root
    data-password: root
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    properties:
      hibernate:
        hbm2ddl:
          auto: update
        dialect=org:
          hibernate:
            dialect: MySQL5InnoDBDialect
    show-sql: true 

代码解释如下。

  • spring.datasource.username:要填写的数据库用 名。

  • spring.datasource.password;要填写的数据库密码

  • spring.jpa.show-sql:开发工具的控制台是否显示 SQL语句 ,建议打开。

  • spring.jpa.properties.hibernate.hbm2ddl.auto的配置属性,其主要作用 是:自动创建、更新、验证数据库表结构 。该参数的几种配置见表

属性 说明
create 每次加载 Hibernate 时都会删除上 次生成的表,然后根据 Model 类再 新生成新表, 怕没有任何 改变也会这样执行,这会导致数据库数据的丢失
create-drop 每次加载 Hibernate 时会根据 Model 类生成表,但是 sessionFactotory 旦关闭 表就会自动被删除
update 最常用的属性,第一次加载Hibernate 时会根据 Model 类自动建立表的结构(前提是先建立好数据库),以后加载 Hibernate 时,会根据 Mode 类自动更新表结构,即使表结构改变了,但表中的数据仍然存在,不会被删除. 要注意的是,当部署到服务器后,表结构是不会被马上建立起来的,要等应用程序第一次运行起来后才会建立 。Update表示如果 entity 实体的字段发生了变化,那么直接在数据库中进行更新
validate 每次加载 Hibernate 时,会验证数据库的表结构,只会和数据库中的表进行比较,不会创建新表,但 是会插入新值

猜你喜欢

转载自blog.csdn.net/qq_45769949/article/details/115045889