spring 配置 SpringBoot+Hibernate+PostgreSQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39521152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Configure SpringBoot+Hibernate+PostgreSQL
提问by zzheads
I'm totally noob in PostgreSQL and configuring Spring web applications, plus all info I could found about this is on Maven or for Eclipse, so very hard for me understand cause I'm using IntelliJ + Gradle. Installed Postgres v 9.5.4.2 on my iMac and started simple web app:
我对 PostgreSQL 和配置 Spring Web 应用程序完全是菜鸟,加上我在 Maven 或 Eclipse 上能找到的所有信息,所以我很难理解,因为我使用的是 IntelliJ + Gradle。在我的 iMac 上安装 Postgres v 9.5.4.2 并启动简单的 Web 应用程序:
UPDATE: All fixes made, M. Deinum, gradle-2.13 is ok for SpringBoot?
更新:所做的所有修复,M. Deinum,gradle-2.13 是否适用于 SpringBoot?
Project structure:
项目结构:
build.gradle:
构建.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
应用程序.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties (no idea why, but dialect attribute is bold red):
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
And error message of course:
当然还有错误信息:
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]
Other code - just usual model (my entities), dao (Crud repositories), service and controllers. Anyway I can't even start it, getting this error message right after boot:
其他代码 - 只是普通模型(我的实体)、dao(Crud 存储库)、服务和控制器。无论如何,我什至无法启动它,启动后立即收到此错误消息:
I will be greatly appreciated for any help to start this program and connect it to PostgeSQL database.
如果您能帮助我启动此程序并将其连接到 PostgeSQL 数据库,我将不胜感激。
UPDATE 2:Moved. Refreshed. Error:
更新 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]
UPDATE 3:Changed name of property in application.property from database to dialect. Application started!
更新 3:将 application.property 中的属性名称从数据库更改为方言。申请开始了!
回答by M. Deinum
You are using Spring Boot (at least that is what you state) but your code shows that you are trying really hard not to use Spring Boot.
您正在使用 Spring Boot(至少这是您所说的),但您的代码表明您正在努力不使用 Spring Boot。
First your Application
class, ideally that should be in a top-level pacakage like com.zzheads.trypostgresql
. With that you can remove the @ComponentScan
and simply replace all the annotations with a simple @SpringBootApplication
annotation. (note the removal of the static
section as well!).
首先是您的Application
班级,理想情况下应该是像com.zzheads.trypostgresql
. 有了它,您可以删除@ComponentScan
并简单地用一个简单的@SpringBootApplication
注释替换所有的注释。(请注意该static
部分的删除!)。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Next your dependencies. Spring Boot provides starter projects those are there for the fact that it saves you hunting for dependencies. Fix those dependencies to use the Spring Boot Starters. Try to use the latests 1.3.7.RELEASE of Spring Boot (as you seem to use the 1.3 line).
接下来是您的依赖项。Spring Boot 提供了启动项目,因为它可以节省您寻找依赖项的时间。修复这些依赖项以使用 Spring Boot Starters。尝试使用 Spring Boot 的最新 1.3.7.RELEASE (因为您似乎使用了 1.3 行)。
springBootVersion = '1.3.7.RELEASE'
Note:The Spring Boot plugin (and dependencies plugin) currently don't work with Gradle 3 (see this).
注意:Spring Boot 插件(和依赖项插件)目前不适用于 Gradle 3(请参阅此)。
Dependencies
依赖关系
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 also provides dependency management so you can remove versions of already managed dependencies.
Spring Boot 还提供依赖项管理,因此您可以删除已管理依赖项的版本。
Next Spring Boot already configures a DataSource
and JPA for you. You don't need to do it yourself. So just remove your DataConfig
.
Next Spring Boot 已经DataSource
为你配置了一个和 JPA。你不需要自己做。所以只需删除您的DataConfig
.
Finally your application.properties
that will be loaded by Spring Boot for you if you put it in the correct location. Move it to one of those locations.
最后application.properties
,如果您将它放在正确的位置,Spring Boot 将为您加载它。将其移动到这些位置之一。
Now to be able to automatically configure the datasource and JPA use the proper property names.
现在能够自动配置数据源和 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
Note:Make sure that the application.properties
is in src/main/resources
and not src/main/java
. If they are in the latter Maven/Gradle will ignore them.
注意:确保application.properties
是 insrc/main/resources
而不是src/main/java
。如果它们在后者中,Maven/Gradle 将忽略它们。
If the entities are in a subpackage of com.zzheads.trypostgresql
they will be automatically detected already and you don't need to add anything. If they aren't add an @EntityScan
annotation to your Application
class to fix that. The same applies to your JPA repositories, if they are in a subpackage you don't need to do anything.
如果实体在com.zzheads.trypostgresql
它们的子包中,它们将被自动检测到,您无需添加任何内容。如果他们没有@EntityScan
向您的Application
课程添加注释来解决这个问题。这同样适用于您的 JPA 存储库,如果它们位于子包中,则您无需执行任何操作。