配置SpringBoot + Hibernate + PostgreSQL

时间:2016-09-15 22:17:33

标签: spring postgresql hibernate spring-boot configuration

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

更新:所有修复,M。Deinum,gradle-2.13对于SpringBoot是否正常?

项目结构:

enter image description here

的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
}

Application.java

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

application.properties(不知道原因,但方言属性为粗体红色):

# 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

当然是错误信息:

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]

其他代码 - 通常的模型(我的实体),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]

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

1 个答案:

答案 0 :(得分:8)

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

首先是Application课程,理想情况下应该是com.zzheads.trypostgresql这样的顶级版本。{1}}。有了它,您可以删除@ComponentScan并简单地用简单的@SpringBootApplication注释替换所有注释。 (注意删除static部分!)。

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

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

springBootVersion = '1.3.7.RELEASE'

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

<强>依赖关系

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")
}

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

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

最后,如果你把它放在correct location中,你的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

注意: 确保application.properties位于src/main/resources而不是src/main/java。如果他们在后者中,Maven / Gradle会忽略它们。

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