SpringBoot+jpa Configuration How to Automatically Create Tables from Entity Classes

  • 2021-12-13 08:06:02
  • OfStack

Directory jpa configuration automatically creates tables according to entity classes 1. Configuration file application. properties2.pom. xml introduction package 3. Write entity classes 4. Run project 5. Aiming at the problem that the database did not generate database tables after the project started jpa automatically generates tables according to Entry 1. Add dependencies 2. Configure application. yml 3. Create Entity

jpa configuration automatically creates tables from entity classes

1. Configuration file application. properties


spring.datasource.url=jdbc:mysql://localhost:3306/bootTable?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

2. pom. xml import package


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

3. Write entity classes


import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
@Entity
// Declare Entity Class 
public class User implements Serializable {
    @Id
    // Declares the entity only 1 Identify the corresponding attribute 
    @GeneratedValue
    // Self-increasing 
    private Integer id;
    @Column(nullable = false, unique = true, length = 32)
    // Length 32 , only 1 Index, nullable Denote true Can be empty, false Can't 
    // Definition of table fields used to declare entity attributes 
    private String userName;
    private String passWord;
    private String email;
    private String nickName;
    private String regTime;
    @Transient
    // Fields that are not mapped to columns 
    private String desc;
    // Omission get And set Method 
}

4. Running the project

Start to generate

5. Aiming at the problem that the database did not generate database tables after the project started

Wrong packet guide: import javax.persistence.*;

Incorrect configuration file: spring. jpa. hibernate. ddl-auto=update

The annotation is not written correctly: don't forget @ Entity

There may be another reason:

The entry file of Sprint is in a subdirectory, which should be one level higher than other service, dao, controller and entity.

For example, if the file service is located in com. demo. metaService, the entry file xxxApplication. java should be under com. demo

jpa automatically generates tables according to Entry

STEP 1 Add dependencies


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

Delete the dependencies on spring-data-jpa, otherwise errors such as not finding bootstrap will occur


<!--        <dependency>-->
<!--            <groupId>org.springframework.data</groupId>-->
<!--            <artifactId>spring-data-jpa</artifactId>-->
<!--            <version>2.1.4.RELEASE</version>-->
<!--        </dependency>-->

2. Configure application. yml

Add the configuration of Jpa automatic generation table


spring:
  jpa: ## Configure automatic table building: updata: There is no new table, but there is a table update operation , The console displays the table building statement 
    hibernate:
      ddl-auto: update
    show-sql: true

3. Create Entity

Personally, it is suggested to create a basic Entity, which is used to create common fields in the table to cooperate with mybatisplus, jackson, SnowFlake, lombok and other libraries. Please import relevant annotations by yourself

BaseEntry.java


@Data// Omission setget Method 
@MappedSuperclass // Label parent class 
@EntityListeners(AuditingEntityListener.class) //jpa Data monitoring 
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"}) // Ignore resolved fields 
public abstract class BaseEntry implements Serializable{
    private static final long serialVersionUID = 1L;
    @Id
    @TableId
    @ApiModelProperty(value = " Only 1 Identification ")
    private String id = String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
    @ApiModelProperty(value = " Founder ")
    @CreatedBy
    private String createBy;
    @CreatedDate
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = " Creation time ")
    private Date createTime;
    @ApiModelProperty(value = " Updater ")
    @LastModifiedBy
    private String updateBy;
    @LastModifiedDate
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = " Update time ")
    private Date updateTime;
    @ApiModelProperty(value = " Delete flag   Default 0")
    @TableLogic
    private Integer delFlag = CommonConstant.STATUS_NORMAL;
}

Business Entry, for reference only


/**
 * tb_bussiness_up_record Entity class 
 *
 * @author
 *
 */
@Data
@Entity
@Table(name = "tb_bussiness_up_record")
@TableName("tb_bussiness_up_record")
public class TbBussinessUpRecord  extends BaseEntry {
    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value = " Dealer ")
    private String bussinessId;
    @ApiModelProperty(value = " Audit time ")
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private String auditTime;
}

Related articles: