spring boot - Schema Created But Tables Not Generated on First Application Run - Stack Overflow

admin2025-04-27  3

I have an entity and my goal is to create the table but also the schema, when the application starts.

@Entity
@Table(schema = "comments", name = "comments")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Comments {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long quotationId;

    @ManyToOne
    @JoinColumn(name = "uid", referencedColumnName = "uid", nullable = false)
    private UserProfile user;

    @Size(min = 5, max = 300)
    private String comment;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "comment_likes", schema = "comments", joinColumns = @JoinColumn(name = "comment_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
    private Set<UserProfile> likedBy = new HashSet<>();

    @OneToMany(mappedBy = "comment")
    private Set<CommentUnreads> commentUnreads = new HashSet<>();

    @CreationTimestamp
    private LocalDateTime createdAt;
}

By removing @Table(schema = "comments", name = "comments"), it will simply create the table into the default schema, and by adding it, it will not do anything.

This is how I create the schema outside of the entity:

@Component
@Order(1)
public class Initializer {

    @Autowired
    private DataSource dataSource;

    @EventListener(ApplicationReadyEvent.class)
    public void loadData() {
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(false, false, "UTF-8", new ClassPathResource("schema.sql"));
        resourceDatabasePopulator.execute(dataSource);
    }
}

schema.sql:

CREATE SCHEMA IF NOT EXISTS comments;

The Problem

By starting the application, schema will be created, but the table will not. By restarting the application again (with the already created schema), table(s) will be created.

To me, it looks like, allthough the class includes @Order(1) (also tried it with 0), it will be executed after the entity. How can I fix this?

转载请注明原文地址:http://anycun.com/QandA/1745708602a91122.html