Spring Data JPA之自动创建数据库表
前言
由于在项目中使用到了Spring Data JPA(Java Persistent API)进行项目开发,并且自己对JPA比较感兴趣想进行学习和了解。首先学习和了解的是JPA自动创建数据库表,通过JPA能够让软件工程师们不用再去手动创建数据表,能够减轻软件工程师们的工作量。
通过本篇博客可以实现使用Spring Data JPA自动创建数据库表,并且可以使表与表之间具有关联性(一对多,多对多,一对一)最后可以通过可视化工具Navicat进行表关系的查看。
Spring Data JPA demo
实现的demo,可以进行下载参考
Spring Data JPA Demo
实现步骤
目前的程序环境是spring boot项目,JDK8.0,MySQL Connector / J 8.0(8.0版本支持java8及其以上的版本,支持5.6、5.7、8.0版本的mysql数据库,支持4.2版本的jdbc)
导入依赖
在spring boot项目中导入JPA依赖和mysql依赖
<!--jpa 启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!--mysql连接器--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
创建实体类
目前有两个实体类,一个基础类
两个实体类分别是UserEntity用户实体类和ClassEntity班级实体类,他们之间具有一对多的关系,一个用户对应着一个班级,一个班级可以有多个用户。
BaseEntity
importorg.springframework.format.annotation.DateTimeFormat;importjavax.persistence.Column;importjavax.persistence.MappedSuperclass;importjava.util.Date;/**
* @author : [WangWei]
* @version : [v1.0]
* @className : BaseEntity
* @description : [基础类]
* @createTime : [2022/11/18 15:32]
* @updateUser : [WangWei]
* @updateTime : [2022/11/18 15:32]
* @updateRemark : [描述说明本次修改内容]
*///@MappedSuperclass的类将不是一个完整的实体类,他将不会映射到数据库表,但是他的属性都将映射到其子类的数据库字段中。@MappedSuperclasspublicclassBaseEntity{//定义字段以及字段的类型和长度和是否允许为null@Column(name ="create_by",columnDefinition ="varchar(32) COMMENT '创建人'",nullable =false)privateString createdBy;@Column(name ="created_id",columnDefinition ="varchar(32) COMMENT '创建人id'",nullable =false)privateLong createdId;@Column(name ="create_time",nullable =false,columnDefinition ="DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'")@DateTimeFormat(pattern ="yyyy-MM-dd HH:mm:ss")privateDate createTime;@Column(name ="updated_by",columnDefinition ="varchar(32) COMMENT '更新人'")privateString updateBy;@Column(name ="updated_id",columnDefinition ="varchar(32) COMMENT '更新人id'")privateLong updateId;定义字段以及字段的类型并默认为当前时间,并当进行修改的时候更新时间为当前实现@Column(name ="update_time",columnDefinition ="DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'")@DateTimeFormat(pattern ="yyyy-MM-dd HH:mm:ss")privateDate updateTime;@Column(name ="is_delete",columnDefinition ="tinyint(1) COMMENT '是否删除(0/1 未删除/删除)'")privateint isDelete=0;@Column(name ="remark",columnDefinition ="varchar(64) COMMENT '备注'")privateString remark;publicStringgetCreatedBy(){return createdBy;}publicvoidsetCreatedBy(String createdBy){this.createdBy = createdBy;}publicDategetCreateTime(){return createTime;}publicvoidsetCreateTime(Date createTime){this.createTime = createTime;}publicStringgetUpdateBy(){return updateBy;}publicvoidsetUpdateBy(String updateBy){this.updateBy = updateBy;}publicLonggetCreatedId(){return createdId;}publicvoidsetCreatedId(Long createdId){this.createdId = createdId;}publicLonggetUpdateId(){return updateId;}publicvoidsetUpdateId(Long updateId){this.updateId = updateId;}publicDategetUpdateTime(){return updateTime;}publicvoidsetUpdateTime(Date updateTime){this.updateTime = updateTime;}publicintgetIsDelete(){return isDelete;}publicvoidsetIsDelete(int isDelete){this.isDelete = isDelete;}publicStringgetRemark(){return remark;}publicvoidsetRemark(String remark){this.remark = remark;}}
UserEntity
importorg.springframework.format.annotation.DateTimeFormat;importjavax.persistence.*;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;/**
* @author : [WangWei]
* @version : [v1.0]
* @className : UserEntity
* @description : [用户实体类]
* @createTime : [2022/11/18 14:57]
* @updateUser : [WangWei]
* @updateTime : [2022/11/18 14:57]
* @updateRemark : [描述说明本次修改内容]
*/@Entity//声明类为实体类@Table(name="jpa_user")//对应创建之后的表名publicclassUserEntityextendsBaseEntity{@Id@Column(name ="user_code",columnDefinition ="bigint(20) COMMENT '学号'",nullable =false)//定义字段名和类型以及长度和备注,和是否允许为nullprivateLong id;@Column(name="user_Name",nullable =false,columnDefinition ="varchar(32) COMMENT '用户名'")privateString userName;@Column(name="pass_word",nullable =false,columnDefinition ="varchar(32) COMMENT '密码'")privateString password;@Column(name="phone_Number",nullable =false,columnDefinition ="varchar(16) COMMENT '手机号'")privateString phoneNumber;@Column(name="sex",columnDefinition ="varchar(2) COMMENT '性别'")privateString sex;@Column(name="birthday",nullable =false,columnDefinition ="datetime COMMENT '生日日期'")@DateTimeFormat(pattern ="yyyy-MM-dd ")privateDate birthday;//定义与ClassEntity之间的关联关系为一对多//cascade:该属性定义类和类之间的级联关系,cascade 的值只能从 CascadeType.PERSIST (级联新建)、 CascadeType.REMOVE (级联删除)、 CascadeType.REFRESH (级联刷新)、 CascadeType.MERGE (级联更新)中选择一个或多个。还有一个选择是使用 CascadeType.ALL ,表示选择全部四项。@OneToMany(cascade =CascadeType.ALL)//在保存关系中的表中,所保存关联的外键字段@JoinColumn(name="user_code")privateList<ClassEntity>classEntities=newArrayList<>();publicLonggetId(){return id;}publicvoidsetId(Long id){this.id = id;}publicList<ClassEntity>getClassEntities(){return classEntities;}publicvoidsetClassEntities(List<ClassEntity> classEntities){this.classEntities = classEntities;}publicStringgetUserName(){return userName;}publicvoidsetUserName(String userName){this.userName = userName;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicStringgetPhoneNumber(){return phoneNumber;}publicvoidsetPhoneNumber(String phoneNumber){this.phoneNumber = phoneNumber;}publicStringgetSex(){return sex;}publicvoidsetSex(String sex){this.sex = sex;}publicDategetBirthday(){return birthday;}publicvoidsetBirthday(Date birthday){this.birthday = birthday;}}
ClassEntity
importjavax.persistence.*;importjavax.validation.constraints.NotBlank;importjavax.validation.constraints.NotNull;/**
* @author : [WangWei]
* @version : [v1.0]
* @className : ClassEntity
* @description : [班级实体]
* @createTime : [2022/11/18 15:47]
* @updateUser : [WangWei]
* @updateTime : [2022/11/18 15:47]
* @updateRemark : [描述说明本次修改内容]
*/@Entity//指定创建之后的表名和创建索引@Table(name ="jpa_class",
indexes ={@Index(name ="index_class_name",columnList ="class_name")})//添加表的注释@org.hibernate.annotations.Table(appliesTo ="jpa_class",comment ="班级表")publicclassClassEntityextendsBaseEntity{@Id@Column(name ="class_id",columnDefinition ="bigint(20) COMMENT '学号'",nullable =false)privateLong id;@Column(name ="class_name",nullable =false,columnDefinition ="varchar(32) COMMENT '班级名'")privateString className;@Column(name="address",nullable =false,columnDefinition ="varchar(128) COMMENT '班级地址'")privateString address;publicLonggetId(){return id;}publicvoidsetId(Long id){this.id = id;}publicStringgetClassName(){return className;}publicvoidsetClassName(String className){this.className = className;}publicStringgetAddress(){return address;}publicvoidsetAddress(String address){this.address = address;}}
编辑application.yml文件配置数据库连接和jpa配置
spring:
datasource:
#mysq 驱动
driver-class-name: com.mysql.cj.jdbc.Driver
#连接数据库的url中配置ip和数据库名称以及时区
url: jdbc:mysql://localhost:3306/spring_jpa?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
username: root
password: root
jpa:
hibernate:
#更新或者创建数据库表结构
ddl-auto: update
#控制台显示SQL
show-sql: true
运行测试
完整的目录结构:
1.运行程序
出现以下界面,表示运行成功
2.在Navicat中查看已创建成功的表
查看相应的表结构和建表语句
3.查看表之间的关系
总结
目前博主只是初步进行了实现,像在项目中进行实际运用还有大量需要学习和掌握的知识,特别是处理表与表之间的关系。
如果博主的文章对您有所帮助,可以评论、点赞、收藏,支持一下博主!!!
版权归原作者 王卫——David 所有, 如有侵权,请联系我们删除。