jpa:springboot -jpa:数据库的一系列的定义数据持久化的标准的体系
学习的目的是:
利用springboot实现对数据库的操作
第一步:添加springboot-data-jpa和数据库的依赖关系
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-jpa</artifactid> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> </dependency>
第二步:编写yml文件的配置;
server: port: 8001 spring: application: name: jih-manage datasource: name: test url: jdbc:mysql://111.231.231.56/jih username: root password: root type: com.alibaba.druid.pool.druiddatasource driver-class-name: com.mysql.jdbc.driver jpa: hibernate: ddl-auto: update show-sql: true
第三步:实体类中使用的注解:
@entity 实体类的注解 @id 映射到表格中id的属性 @gernertervalue 添加其自增的属性;
第四步:启动项目是否生成表格
补充的知识点:
根据实体类生成数据库的表配置文件有俩种方式分别是yml和properties文件进行配置
yml文件:
spring: datasource: driver-class-name: com.mysql.jdbc.driver url: jdbc:mysql://127.0.0.1:3306/facemap username: root password: root jpa: hibernate: ddl-auto: update show-sql: true
properties文件的写法:
spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.url=jdbc:mysql://localhost:3306/dbgirl?characterencoding=utf8 spring.datasource.username=root spring.datasource.password=root spring.jpa.show-sql= true spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.dialect=org.hibernate.dialect.mysql5dialect spring.jackson.serialization.indent_output=false
有更加详细介绍
首先我是通过maven创建了一个spring boot的工程,引入了spring data jpa,结果实体类创建好之后,运行工程却没有在数据库中自动创建数据表。
找了半天发现是一个配置的问题:
hibernate.ddl-auto节点的配置,这个配置有两种方式去配置,我使用的是通过properties文件去配置:
#datasource config spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.url=jdbc:mysql://localhost:6033/data_service?characterencoding=utf8 spring.datasource.username=root spring.datasource.password=root spring.jpa.show-sql= true spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.dialect=org.hibernate.dialect.mysql5dialect spring.jackson.serialization.indent_output=false
hibernate.hbm2ddl.auto节点的值有几个create、create-drop、update、validate、none
- create:每次加载hibernate会自动创建表,以后启动会覆盖之前的表,所以这个值基本不用,严重会导致的数据的丢失。
- create-drop : 每次加载hibernate时根据model类生成表,但是sessionfactory一关闭,表就自动删除,下一次启动会重新创建。
- update:加载hibernate时根据实体类model创建数据库表,这是表名的依据是@entity注解的值或者@table注解的值,sessionfactory关闭表不会删除,且下一次启动会根据实体model更新结构或者有新的实体类会创建新的表。
- validate:启动时验证表的结构,不会创建表
- none:启动时不做任何操作
实体类的写法:
package com.example.demo; import javax.persistence.entity; import javax.persistence.generatedvalue; @entity //实体类的注解 public class girl { @id //@id注意选择这个javax.persistence @generatedvalue private integer id; private string cupsize; private integer age; public girl() { } public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getcupsize() { return cupsize; } public void setcupsize(string cupsize) { this.cupsize = cupsize; } public integer getage() { return age; } public void setage(integer age) { this.age = age; } }
第五步:启动项目即可
到此这篇关于springboot根据实体类生成表的实现方法的文章就介绍到这了,更多相关springboot 实体类生成表内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论