Springboot根据实体类生成数据库表
springboot数据库(一)-springboot-JPA
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
有更加详细介绍 参考网址;
实体类的写法:
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; } }
第五步:启动项目即可