我又回到了 Java 世界,并尝试使用 JPA、Hibernate 和 PostgreSQL 配置一个新的 Spring Web 应用程序。
我发现了很多带有各种 XML 配置文件的旧示例,我想知道是否有一种首选的新方法可以在不依赖 XML 文件创作的情况下执行此配置。
我需要配置的一些东西是 hibernate sql 方言、驱动程序等。
将以下片段放入带有注释的类中@Configuration
and @EnableTransactionManagement
Hibernate/JPA(编辑packagesToScan字符串):
@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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)