avatar
get spring boot to automatically create database schema Spring Boot

• To practice creating a database schema automatically using our code snippet, you should first have a Spring Boot project available.

+- src
    +- main
        +- java
        +-  +- com
        +-      +- flagtick
        +-           +- entity
        +-                +- User.java
        +-           +- MySpringBoot.java
        +- resource
            +- application.properties
            +- log4j2.xml

• Let's delve more deeply into each class that indicates the way to initialize entities and the database schema, which enables you to generate a database on any database management system.

» application.properties

server.port=8080

spring.datasource.url=jdbc:mysql://localhost:3306/springbootcrud?useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#  Use for communicating with a MySQL database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

# This is one of behavior of Hibernate and automatically update the database schema based on any
# changes to the entity classes
spring.jpa.hibernate.ddl-auto=create

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

» MySpringBoot.java

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MySpringBoot {

   public static void main(String[] args) throws Exception {
      SpringApplication.run(MySpringBoot.class, args);
   }
}

» log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="ConsoleAppender"/>
        </Root>
        <Logger name="org.hibernate.SQL" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender" />
        </Logger>
    </Loggers>
</Configuration>

» User.java

package com.flagtick.entity;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Column(nullable = false)
    private String email;

    private String avatar;

    private LocalDateTime emailVerifiedAt;

    private String password;

    private String userEncrypt;

    private String userFirebaseId;

    private String rememberToken;

    private LocalDateTime expiresIn;

    @Column(nullable = false)
    private final Boolean isMigration = true;

    @Column(nullable = false)
    private final Integer status = 1;

    @Column(nullable = false)
    private final Boolean isEditable = true;

    private final String typeOfUser = "external";

    private String lang;

    @CreationTimestamp
    private LocalDateTime createdAt;

    @UpdateTimestamp
    private LocalDateTime updatedAt;
}  
  • @Entity is an annotation used in Java Persistence API (JPA) to mark a class as a persistent entity, which means it will be mapped to a database table. However, if you are not using JPA or a relational database, @Entity may not be relevant or appropriate for your use case.
  • @Table is an annotation used to specify the table name and schema for an entity class. 
  • @Id annotation marks the primary key field of this entity.
  • @GeneratedValue annotation specifies how the primary key field should be generated. In this case, it is set to `GenerationType.IDENTITY`, which means that the primary key is generated by the database.
  • @Column annotation is used to specify the column name, constraints, and other properties for a field in the table.
  • @CreationTimestamp annotation is used to mark the createdAt field, indicating that the value of this field should be set to the current timestamp when new User object is persisted for the first time.
  • @UpdateTimestamp annotation is used to mark the updatedAt field, indicating that the value of this field should be automatically updated to the current timestamp whenever User object is updated and persisted.

Note: In certain scenarios, the `@CreationTimestamp` and `@UpdateTimestamp` annotations may not function properly. If this occurs, you will need to include the necessary dependencies in `pom.xml` file.

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.4.32.Final</version>
</dependency>

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>5.4.32.Final</version>
</dependency>

• Visit website https://projectlombok.org/features and take advantage of annotations to reduce boilerplate code in Java classes. In the context of Java entity classes, Lombok can be used to generate getter and setter methods, constructors, and other methods that are commonly used in entity classes.

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.24</version>
   <scope>provided</scope>
</dependency>

Here's an example of how you could modify the User class to use Lombok annotations:

@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {}

• After that, you can start Spring Boot application.

You need to login to do this manipulation!