在没有XML的情况下配置JPA / Hibernate / PostgreSQL

我正在回到Java世界,我正在尝试使用JPA,Hibernate和PostgreSQL配置一个新的Spring Web应用程序。

我发现了许多带有各种XML配置文件的旧示例,我想知道是否有一种首选的新方法来执行此配置而不依赖于XML文件创作。

我需要配置的一些东西是hibernate sql方言,驱动程序等。

将以下片段放入使用@Configuration@EnableTransactionManagement注释的类中

Hibernate / JPA(编辑packagesToScan String):

 @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.XY.model" }); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } Properties additionalProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", "update"); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect"); properties.setProperty("hibernate.show_sql", "true"); return properties; } 

DataSource(编辑用户名,密码和主机地址):

 @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl("jdbc:postgresql://localhost:port/DB_NAME"); dataSource.setUsername("root"); dataSource.setPassword(""); return dataSource; } 

交易经理:

 @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(emf); return transactionManager; } 

如果您要使用spring ,我建议使用Spring Boot ,它提供了许多自动配置。 你可以使用application.properties来配置dialect和东西:

 spring.datasource.url =  spring.datasource.username =  spring.datasource.password =  spring.datasource.driver-class-name = org.postgresql.Driver 

Spring Boot提供了许多入门包 ,可以轻松地将jar添加到类路径中。 这些Starter Packages仅提供在开发特定类型的应用程序时可能需要的依赖项。 由于您正在开发一个可能需要数据访问的Web应用程序,您应该将它们添加到您的pom.xml

  org.springframework.boot spring-boot-starter-parent 1.3.1.RELEASE   1.8    org.springframework.boot spring-boot-starter-data-jpa   org.springframework.boot spring-boot-starter-web   org.postgresql postgresql   

基本上,spring boot会根据您添加的jar依赖项来猜测您将如何配置应用程序。 spring-boot-starter-data-jpa提供以下关键依赖项:

  • Hibernate – 最受欢迎的JPA实现之一。
  • Spring Data JPA – 使实现基于JPA的存储库变得容易。
  • Spring ORMs – 来自Spring Framework的核心ORM支持。

您可以使用spring.jpa.*属性显式配置JPA设置。 例如,要创建和删除表,可以将以下内容添加到application.properties

 spring.jpa.hibernate.ddl-auto=create-drop 

你可以在这里阅读更多关于弹簧靴的信息