Home > OS >  Spring can't initialize database in postgres
Spring can't initialize database in postgres

Time:10-27

I try to learn one-to-many(unidirectional) relation in hibernate. I create a simple project with post and comment model. I'm trying to initialize my database in postgres using sql file, but hibernate can't create post table. Anyone can tell me what I'm doing wrong? I'm trying use some solution from stackoverfow but it isn't working, or maybe I do some stupid mistake. Thanks for help.

This is error what I get:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of class path resource [data.sql]: INSERT INTO post(title, content, created) values ('dupa', 'Content 1', CURRENT_TIMESTAMP); nested exception is org.postgresql.util.PSQLException: ERROR: the "post" relationship does not exist

This is model, repository, service and controlle which I create:

     @Entity
        @Getter
        @Setter
        public class Post {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;
            private String title;
            private String content;
            private LocalDateTime created;
            @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
            private List<Comment> comments;
        
            public Post() {
            }
        }
    
        @Entity
        @Getter
        @Setter
        public class Comment {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;
            private String content;
            private LocalDateTime created;
        
            public Comment() {
            }
        }
    
            @Repository
        public interface PostRepository extends JpaRepository<Post, Long> {
        }
    
    @Service
    @AllArgsConstructor
    public class PostService {
    
        private final CommentRepository commentRepository;
        private final PostRepository postRepository;
    
        public List<Post> getPosts(){
            return postRepository.findAll();
        }
    }
    
        @RestController
        @RequiredArgsConstructor
        public class PostController {
            private final PostService postService;
            private final CommentService commentService;
        
            @GetMapping("/posts")
            public List<Post> getPosts(){
                return postService.getPosts();
            }
        }
    

This is my application.properties:

spring.jpa.hibernate.ddl-auto=create-drop
spring.sql.init.mode=always
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postcommentapi
spring.datasource.username=amso
spring.datasource.password=1234
spring.sql.init.data-locations = classpath:/create_db_content
spring.jpa.show-sql=true

My pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.konrad</groupId>
    <artifactId>postcommentapi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>postcommentapi</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</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-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

CodePudding user response:

You need to give the table name in the entity class

@Entity
@Getter
@Setter
@Table(name = "post")
        public class Post {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;
            private String title;
            private String content;
            private LocalDateTime created;
            @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
            private List<Comment> comments;
        
            public Post() {
            }
        }

Also in the Comment entity

@Entity
@Getter
@Setter
@Table(name = "comment")
        public class Comment {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;
            private String content;
            private LocalDateTime created;
        
            public Comment() {
            }
        }

CodePudding user response:

spring.sql.init.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/postcommentapi
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.datasource.initialization-mode=always
#spring.sql.init.mode=always
spring.sql.init.data-locations= classpath:/import.sql
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

I was trying to change some options in applications.properties. Ultimately this form work for me, but this isn't a good solve of my problem because this line:

deprecated option initialization mode

is deprecated in my version of spring. I should use:

spring.sql.init.mode=always

I don't now why it's works with depricated option.

  • Related