配置SpringBoot + Hibernate + PostgreSQL

zzh*_*ads 7 postgresql configuration spring hibernate spring-boot

我在PostgreSQL中完全是noob并配置Spring Web应用程序,加上我在Maven或Eclipse上找到的所有信息,所以我很难理解因为我正在使用IntelliJ + Gradle.在我的iMac上安装了Postgres v 9.5.4.2并启动了简单的Web应用程序:

更新:所有修复,M.Deinum,gradle-2.13对于SpringBoot是否可以?

项目结构:

在此输入图像描述

的build.gradle:

buildscript {
    ext {
        springBootVersion = '1.3.7.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'TryPostgreSQL'
    version = '0.0.1-SNAPSHOT'
}

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.springframework.boot:spring-boot-starter-security'
    compile 'org.springframework.boot:spring-boot-starter-aop'
    compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4'
    compile 'com.google.code.gson:gson'
    compile 'org.postgresql:postgresql'

    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile("org.dbunit:dbunit:2.5.1")
    testCompile("com.github.springtestdbunit:spring-test-dbunit:1.2.1")
    testCompile("net.sourceforge.htmlunit:htmlunit:2.20")
    testCompile("org.easytesting:fest-assert:1.4")
    testCompile ("org.springframework.security:spring-security-test")
}

task wrapper(type: Wrapper) {
    gradleVersion = '3.0'
}

task stage {
    dependsOn build
}
Run Code Online (Sandbox Code Playgroud)

Application.java

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

application.properties(不知道为什么,但dialect属性是粗体红色):

# Details for our datasource
spring.datasource.url = jdbc:postgresql://localhost:5432/database
spring.datasource.username = postgres
spring.datasource.password = postgres

# Hibernate properties
spring.jpa.database = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql = false
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.jpa.properties.hibernate.format_sql=true
Run Code Online (Sandbox Code Playgroud)

当然还有错误信息:

2016-09-16 09:17:19.978  WARN 773 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
2016-09-16 09:17:19.985  INFO 773 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2016-09-16 09:17:19.996 ERROR 773 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
Run Code Online (Sandbox Code Playgroud)

其他代码 - 只是通常的模型(我的实体),dao(Crud存储库),服务和控制器.无论如何我甚至无法启动它,在启动后立即收到此错误消息:

对于启动此程序并将其连接到PostgeSQL数据库的任何帮助,我将不胜感激.

更新2: 移动.装修一新.错误:

Properties configuration failed validation
2016-09-16 09:41:53.696 ERROR 883 --- [           main] o.s.b.b.PropertiesConfigurationFactory   : Field error in object 'spring.jpa' on field 'database': rejected value [org.hibernate.dialect.PostgreSQLDialect]; codes [typeMismatch.spring.jpa.database,typeMismatch.database,typeMismatch.org.springframework.orm.jpa.vendor.Database,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spring.jpa.database,database]; arguments []; default message [database]]; default message [Failed to convert property value of type [java.lang.String] to required type [org.springframework.orm.jpa.vendor.Database] for property 'database'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [org.springframework.orm.jpa.vendor.Database] for value 'org.hibernate.dialect.PostgreSQLDialect'; nested exception is java.lang.IllegalArgumentException: No enum constant org.springframework.orm.jpa.vendor.Database.org.hibernate.dialect.PostgreSQLDialect]
Run Code Online (Sandbox Code Playgroud)

更新3: 将application.property中的属性名称从数据库更改为方言.申请开始了!

M. *_*num 8

您正在使用Spring Boot(至少这是您所说的),但您的代码显示您正在努力不使用Spring Boot.

首先是你的Application班级,理想情况下应该是顶级的pacakage com.zzheads.trypostgresql.有了它,您可以删除@ComponentScan并简单地用简单的@SpringBootApplication注释替换所有注释.(注意删除该static部分!).

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来你的依赖项.Spring Boot提供了初学者项目,因为它可以节省您寻找依赖项的事实.修复这些依赖项以使用Spring Boot Starters.尝试使用最新的1.3.7.RELEASE Spring Boot(因为你似乎使用了1.3行).

springBootVersion = '1.3.7.RELEASE'
Run Code Online (Sandbox Code Playgroud)

注意: Spring Boot插件(和依赖项插件)目前不适用于Gradle 3(请参阅此内容).

依赖

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.springframework.boot:spring-boot-starter-security'
    compile 'org.springframework.boot:spring-boot-starter-aop'
    compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4'
    compile 'com.google.code.gson:gson'
    compile 'org.postgresql:postgresql'

    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile("org.dbunit:dbunit:2.5.1")
    testCompile("com.github.springtestdbunit:spring-test-dbunit:1.2.1")
    testCompile("net.sourceforge.htmlunit:htmlunit:2.20")
    testCompile("org.easytesting:fest-assert:1.4")
    testCompile ("org.springframework.security:spring-security-test")
}
Run Code Online (Sandbox Code Playgroud)

Spring Boot还提供依赖关系管理,因此您可以删除已管理的依赖项的版本.

Next Spring Boot已经DataSource为您配置了一个和JPA.你不需要自己动手.所以只需删除你的DataConfig.

最后application.properties,如果你将它放在正确的位置,那么Spring Boot会为你加载它.将其移动到其中一个位置.

现在能够自动配置数据源和JPA使用适当的属性名称.

# Details for our datasource
spring.datasource.url = jdbc:postgresql://localhost:5432/database
spring.datasource.username = postgres
spring.datasource.password = postgres

# Hibernate properties
spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql = false
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.jpa.properties.hibernate.format_sql=true
Run Code Online (Sandbox Code Playgroud)

注意: 确保application.propertiessrc/main/resources和不src/main/java.如果他们在后者中,Maven/Gradle会忽略它们.

如果实体位于子包中,则com.zzheads.trypostgresql它们将自动被检测到,您无需添加任何内容.如果他们没有@EntityScan为您的Application类添加注释来修复它.这同样适用于您的JPA存储库,如果它们位于子包中,则您不需要执行任何操作.