配置 jdbcConfig.properites
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/jpaTestjdbc.username=rootjdbc.password=123456
编写配置类
@Configuration@ComponentScan(value = "com.example")@PropertySource(value = "classpath:jdbcConfig.properties")@EnableTransactionManagement@EnableJpaRepositories(basePackages = "com.example.dao", transactionManagerRef = "transactionManager",entityManagerFactoryRef = "entityManagerFactory")public class SpringConfiguration { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource(){ ComboPooledDataSource dataSource = new ComboPooledDataSource(); try{ dataSource.setDriverClass(driver); dataSource.setJdbcUrl(url); dataSource.setUser(username); dataSource.setPassword(password); return dataSource; } catch (PropertyVetoException e) { throw new RuntimeException(e.getMessage()); } } @Bean public PersistenceProvider persistenceProvider(){ return new HibernatePersistenceProvider(); } @Bean public JpaVendorAdapter jpaVendorAdapter(){ HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setShowSql(true); jpaVendorAdapter.setGenerateDdl(false); jpaVendorAdapter.setDatabase(Database.MYSQL); jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); return jpaVendorAdapter; } @Bean public JpaDialect jpaDialect(){ return new HibernateJpaDialect(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( @Autowired DataSource dataSource, @Autowired PersistenceProvider persistenceProvider, @Autowired JpaVendorAdapter jpaVendorAdapter, @Autowired JpaDialect jpaDialect){ LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(dataSource); factory.setPackagesToScan("com.example.domain"); factory.setPersistenceProvider(persistenceProvider); factory.setJpaVendorAdapter(jpaVendorAdapter); factory.setJpaDialect(jpaDialect); return factory; } @Bean public PlatformTransactionManager transactionManager(@Autowired EntityManagerFactory entityManagerFactory){ JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory); return txManager; }}
编写JPA 接口
@Repositorypublic interface ICustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {}
编写测试类
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = {SpringConfiguration.class}) //指定 Spring 容器的配置信息public class ICustomerDaoTest { @Autowired private ICustomerDao customerDao; .....}