Spring Boot 通过实体类映射生成数据库中的表
Spring Boot +Hibernate + jpa 通过实体映射生成数据库中的表
不废话,上代码
一,POM 配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
二,配置文件
# 根据实体类创建数据库表 # create 启动时删数据库中的表,然后创建,退出时不删除数据表 # create-drop 启动时删数据库中的表,然后创建,退出时删除数据表 如果表不存在报错 # update 如果启动时表格式不一致则更新表,原有数据保留 # validate 项目启动表结构进行校验 如果不一致则报错
spring: jpa: hibernate: ddl-auto: update show-sql: true naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
三,定义实体类
import lombok.Setter; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "tableName") @org.hibernate.annotations.Table(appliesTo = "tableName",comment="表注释") @Setter public class _1_AAAAA { private String operationId; private String enable; private Date createTime; private String createBy; private Date updateTime; private String updateBy; private String remark; private Long id; public void setId(Long id) { this.id = id; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(length = 20) public Long getId() { return id; } @Column(name = "operation_id", columnDefinition = " VARCHAR(300) DEFAULT NULL COMMENT '业务ID' ") public String getOperationId() { return operationId; } @Column(name = "enable", columnDefinition = " CHAR DEFAULT 'Y' COMMENT '是否有效' ") public String getEnable() { return enable; } @Column(name = "create_time", columnDefinition = " DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT '创建时间' ") public Date getCreateTime() { return createTime; } @Column(name = "create_by", columnDefinition = " VARCHAR(300) DEFAULT NULL COMMENT '创建人' ") public String getCreateBy() { return createBy; } @Column(name = "update_time", columnDefinition = " DATETIME DEFAULT CURRENT_TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间' ") public Date getUpdateTime() { return updateTime; } @Column(name = "update_by", columnDefinition = " VARCHAR(300) DEFAULT NULL COMMENT '更新人' ") public String getUpdateBy() { return updateBy; } @Column(name = "remark", columnDefinition = " VARCHAR(500) DEFAULT NULL COMMENT '备注' ") public String getRemark() { return remark; }
项目启动,数据库表就创建成功!!