在Spring Boot中配置JPA的方法有以下几种:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.cache.use_minimal_puts=true
spring.jpa.properties.hibernate.cache.use_structured_entries=true
spring.jpa.properties.hibernate.cache.infinispan.statistics=true
spring.jpa.properties.hibernate.cache.infinispan.debug=true
spring.jpa.properties.hibernate.cache.infinispan.eviction.strategy=LRU
spring.jpa.properties.hibernate.cache.infinispan.eviction.max-entries=10000
spring.jpa.properties.hibernate.cache.infinispan.eviction.wake-up-interval=2000
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: 123456
jpa:
show-sql: true
hibernate:
ddl-auto: update
dialect: org.hibernate.dialect.MySQL5Dialect
format_sql: true
use_sql_comments: true
id:
new_generator_mappings: false
enable_lazy_load_no_trans: true
properties:
hibernate.cache.use_second_level_cache: true
hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
hibernate.cache.use_query_cache: true
hibernate.cache.use_minimal_puts: true
hibernate.cache.use_structured_entries: true
hibernate.cache.infinispan.statistics: true
hibernate.cache.infinispan.debug: true
hibernate.cache.infinispan.eviction.strategy: LRU
hibernate.cache.infinispan.eviction.max-entries: 10000
hibernate.cache.infinispan.eviction.wake-up-interval: 2000
@Configuration
@EnableJpaRepositories(basePackages = "com.example.repository")
public class JpaConfig {
@Autowired
private DataSource dataSource;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.example.entity");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
return em;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
}
无论使用哪种配置方式,都需要引入相关的依赖,如spring-boot-starter-data-jpa、mysql-connector-java等。