skip to Main Content

I’m using Java, Spring Boot, Hibernate and Lombok as a Maven project with PostgreSQL database.
It used to work, but after my next changes hibernate can not create tables automatically to database.
What I tried is:

  • Changing packages localization
  • changing my application properties
  • changing from
    spring.jpa.hibernate.ddl-auto=update to
    spring.jpa.hibernate.ddl-auto=create but nothing worked for me.
  • Connecting with other, new database but also nothing, no new tables.
  • I also read a lot of stackoverflow topics of "Hibernate does not
    create tables automatically" but nothing that helped me.
  • Commented every other class to avoid possible conflicts / new changes.
    I even tried to comment every class except Location.class but didn’t help…

I have no idea what could happen.

When I start the server, location table is not created in my database, but when I type

FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'comparator' AND pid <> pg_backend_pid();

There are 4 connections after server starts, so it should work.

application.properties:

spring.datasource.url = ${SPRING_DATASOURCE_URL}
spring.datasource.username = ${SPRING_DATASOURCE_USERNAME}
spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD}

spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=update

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>pl.comparator.renting.car</groupId>
    <artifactId>comparator</artifactId>
    <version>0.0.2-SNAPSHOT</version>
    <name>comparator</name>
    <description>Car Renting Comparator Web App</description>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <!-- exclude built in spring boot logging as we use log4j2 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- logging dependencies -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.19.0</version>
        </dependency>

        <!-- database dependencies -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.7.1</version>
        </dependency>

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

        <dependency>
            <groupId>jakarta.persistence</groupId>
            <artifactId>jakarta.persistence-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- entity dependencies -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>8.0.1.Final</version>
        </dependency>

        <!-- testing dependencies -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.10.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>5.8.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

ComparatorApplication


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.lang.invoke.MethodHandles;

@SpringBootApplication
public class ComparatorApplication {
    private static final Logger log = LogManager.getLogger(MethodHandles.Lookup.class);

    public static void main(String[] args) {
        SpringApplication.run(ComparatorApplication.class, args);
        log.info("Testing log which informs that Comparator Application has started successfully.");
    }
}

Location.java


import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.Objects;

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Location {

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

    @Size(min = 2, max = 50, message = "City name should be between 2 and 50 characters")
    @NotBlank(message = "City name cannot be empty")
    private String city;

    @Pattern(regexp = "^\d{2}-\d{3}$", message = "Invalid zip code format")
    private String zipCode;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Location location = (Location) o;
        return getId() == location.getId() && Objects.equals(getCity(), location.getCity()) && Objects.equals(getZipCode(), location.getZipCode());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getId(), getCity(), getZipCode());
    }
}

Console run log:

"

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.2.1)

00:00:27.266 [background-preinit] INFO  org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 8.0.1.Final
00:00:27.325 [main] INFO  comparator.configuration.ComparatorApplication - Starting ComparatorApplication using Java 17 with PID 4688 
00:00:27.332 [main] INFO  comparator.configuration.ComparatorApplication - No active profile set, falling back to 1 default profile: "default"
00:00:28.016 [main] INFO  org.springframework.data.repository.config.RepositoryConfigurationDelegate - Bootstrapping Spring Data JPA repositories in DEFAULT mode.
00:00:28.037 [main] INFO  org.springframework.data.repository.config.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 4 ms. Found 0 JPA repository interfaces.
00:00:28.575 [main] INFO  org.springframework.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port 8080 (http)
sty 10, 2024 12:00:28 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
sty 10, 2024 12:00:28 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Tomcat]
sty 10, 2024 12:00:28 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/10.1.17]
sty 10, 2024 12:00:28 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring embedded WebApplicationContext
00:00:28.653 [main] INFO  org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 1256 ms
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.
00:00:28.896 [main] INFO  org.hibernate.Version - HHH000412: Hibernate ORM core version 6.4.1.Final
00:00:28.932 [main] INFO  org.hibernate.cache.internal.RegionFactoryInitiator - HHH000026: Second-level cache disabled
00:00:29.167 [main] INFO  org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo - No LoadTimeWeaver setup: ignoring JPA class transformer
00:00:29.800 [main] INFO  org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator - HHH000489: No JTA platform available (set 'hibernate.transaction.jta.platform' to enable JTA platform integration)
00:00:29.805 [main] INFO  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default'
sty 10, 2024 12:00:30 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
00:00:30.229 [main] INFO  org.springframework.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port 8080 (http) with context path ''
00:00:30.248 [main] INFO  comparator.configuration.ComparatorApplication - Started ComparatorApplication in 3.311 seconds (process running for 4.027)
00:00:30.251 [main] INFO  java.lang.invoke.MethodHandles.Lookup - Testing log which informs that Comparator Application has started successfully.

2

Answers


  1. Chosen as BEST ANSWER

    I found the cause. The problem was the location of the packages and the main @SpringBootApplication location...

    Before it was as on the screenshot below:

    enter image description here

    Which should work, as I've read other articles on what packages should look like.

    But it turned out that the main runtime file MUST be above the rest of the packages and classes as on the screenshot below:

    enter image description here

    Now it is creating the tables properly.


  2. Create is an invalid value (see here).

    Hibernate property values are none, validate, update, create-drop

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search