我正在重新涉足Java领域,我试图使用JPA、Hibernate和PostgreSQL配置一个新的Spring Web应用程序。
我发现很多旧的例子都是使用各种XML配置文件,我想知道是否有更喜欢的新方法来进行配置而不依赖于XML文件编写。
我需要配置的一些内容包括Hibernate SQL方言、驱动程序等。
我发现很多旧的例子都是使用各种XML配置文件,我想知道是否有更喜欢的新方法来进行配置而不依赖于XML文件编写。
我需要配置的一些内容包括Hibernate SQL方言、驱动程序等。
@Configuration
和@EnableTransactionManagement
注释的类中:@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;
}
数据源(编辑用户名、密码和主机地址):
@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 = <jdbcurl>
spring.datasource.username = <username>
spring.datasource.password = <password>
spring.datasource.driver-class-name = org.postgresql.Driver
Spring Boot提供了许多Starter Packages,可以轻松地将jar添加到您的类路径中。这些Starter Packages只是提供了在开发特定类型的应用程序时可能需要的依赖项。由于您正在开发可能需要数据访问的Web应用程序,因此应将以下内容添加到您的pom.xml
文件中:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
spring-boot-starter-data-jpa
提供以下关键依赖项:
spring.jpa.*
属性显式地配置 JPA 设置。例如,要创建和删除表格,可以将以下内容添加到你的 application.properties
文件中:spring.jpa.hibernate.ddl-auto=create-drop
application.properties
。您还可以使用 YAML 文件、环境变量和命令行参数来配置应用程序。 - Ali Dehghani