Spring Boot: Hibernate не рисует таблицы

362
01 февраля 2018, 18:09

Собираю первый проект на Spring Boot.

Проект собирается и поднимается, но Hibernate не рисует таблицы по сущностям, как должен (то есть, вообще никак). При этом, база подключена (Connection Success).

build.gradle:

buildscript {
    ext {
        springBootVersion = '2.0.0.M7'
    }
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath 'gradle.plugin.com.ewerk.gradle.plugins:querydsl-plugin:1.0.9'
    }
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'com.ewerk.gradle.plugins.querydsl'
group = 'ru.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.kafka:spring-kafka')
//  compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.security:spring-security-test')
}
querydsl {
    jpa = true
    querydslSourcesDir = "$buildDir/generated/source/apt/main"
}

application.properties:

# database connection
spring.datasource.url=jdbc:postgresql://localhost:5432/example
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=user
spring.datasource.password=12345
# jpa / hibernate
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
# Fix Postgres JPA Error:
# Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented.
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

Точка входа:

@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories("ru.example.repository")
@ComponentScan(basePackages = {
        "ru.example.controller",
        "ru.example.service",
        "ru.example.config",
        "ru.example.dto",
        "ru.example.util"})
@EntityScan("ru.example.entity")
@SpringBootApplication
public class HealthMeterApplication {
    public static void main(String[] args) {
        SpringApplication.run(HealthMeterApplication.class, args);
    }
}

Репозиторий:

@Repository
public interface TestRepository extends CrudRepository<TestEntity, Long> {
}

Сущности:

@MappedSuperclass
@JsonIgnoreProperties(value = {"created"}, ignoreUnknown = true)
public abstract class AbstractEntity implements Serializable {
    private static final int START_SEQ = 1000000000;
    private Long id;
    private LocalDateTime created;
    @Id
    @SequenceGenerator(name = "global_seq", sequenceName = "global_seq", allocationSize = 1, initialValue = START_SEQ)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "global_seq")
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @Column(name = "created", updatable = false)
    public LocalDateTime getCreated() {
        return created;
    }
    private void setCreated(LocalDateTime created) {
        this.created = created;
    }
    @PrePersist
    void onCreate() {
        if (Objects.isNull(this.getCreated())) {
            this.setCreated(LocalDateTime.now());
        }
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        AbstractEntity that = (AbstractEntity) o;
        if (id != null ? !id.equals(that.id) : that.id != null) return false;
        return created != null ? created.equals(that.created) : that.created == null;
    }
    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (created != null ? created.hashCode() : 0);
        return result;
    }

==========

@Entity
@Table(name = "test")
public class TestEntity extends AbstractEntity {
    private Long name;
    @Column(name = "name")
    public Long getName() {
        return name;
    }
    public void setName(Long name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        TestEntity entity = (TestEntity) o;
        return name != null ? name.equals(entity.name) : entity.name == null;
    }
    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}
Answer 1

Измените свойство spring.jpa.hibernate.ddl-auto на:

  • update - Для обновления схемы
  • create - Для создания схемы и удаление предыдущих данных
  • create-drop - Для создания схемы и удаление схемы по окончанию сессии

    Подробности можно найти здесь http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch03.html#configuration-optional

  • READ ALSO
    Android область видимости и взаимодействия

    Android область видимости и взаимодействия

    У меня есть одна функция которая работает как сервис, но она не срабатывает, я не могу понять почемуВот код функции:

    235
    Как протестировать приватный Injected обьект?

    Как протестировать приватный Injected обьект?

    Как протестировать приватный Injected обьект?

    324
    JOIN на уровне базы данных или на уровне приложения?

    JOIN на уровне базы данных или на уровне приложения?

    Имется две таблицы: Судья и СоревнованиеОдно соревнование судят несколько судей, один и тот же судья может судить несколько соревнований

    244