SpringDataJpa学习记录----02三种配置方式
在Spring Data JPA中,配置实体管理器的方式主要有三种:
- 传统的XML配置方式。
- Spring Java Configuration方式。
- 使用Spring Boot的自动配置。
以下是这三种配置方式的简要示例:
- XML配置方式:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.example.yourpackage" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
- Spring Java Configuration方式:
@Configuration
@EnableTransactionManagement
public class PersistenceConfig {
@Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.example.yourpackage");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.show_sql", true);
em.setJpaPropertyMap(properties);
em.afterPropertiesSet();
return em.getObject();
}
@Bean
public DataSource dataSource() {
// 配置数据源
}
}
- Spring Boot自动配置:
在Spring Boot中,通常使用application.properties
或application.yml
文件进行配置。
# application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
在Spring Boot中,通常不需要手动配置实体管理器,Spring Boot的自动配置功能会自动为你配置好。
评论已关闭