Home > Enterprise >  How do i create new table in database from same entity JPA Spring boot?
How do i create new table in database from same entity JPA Spring boot?

Time:10-27

I want to create a new table every day with the full date as table name if the day is new create table for the that day

I have seen that when I change @Table(name="") name to a new string it make a new table but I can't automate this work

@Entity
@Table(name="orders_25_10_2021")
public class game2data {
@Id
private int cid;
private String name;
private Integer address;
private Integer gender;
private String date;
private String Done;

In simple words, I want to pass the name of @Table(name="") as a variable with dynamic according to date.

CodePudding user response:

You can achieve this custom naming strategy by extending SpringPhysicalNamingStrategy and overriding its toPhysicalTableName method :

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TableNamingStrategy extends SpringPhysicalNamingStrategy {
  private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd_MM_YYYY");
  public static final PhysicalNamingStrategyStandardImpl INSTANCE =
      new PhysicalNamingStrategyStandardImpl();

  @Override
  public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
    if (!name.getText().equals("game2data"))
      return name;
    StringBuilder customName =
        new StringBuilder("orders").append('_').append(DATE_FORMATTER.format(LocalDate.now()));
    return new Identifier(customName.toString(), name.isQuoted());
  }
}

and registering it in your application.properties:

spring.jpa.hibernate.naming.physical-strategy=com.stackoverflow.questions.TableNamingStrategy

and removing the @Table annotation from the game2data entity.

  • Related