1.在配置文件中写入数据库信息
application.properties
配置如下
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
2.创建Spring配置类,定义DataSource用来读取application.properties
中的配置
@Configuration
public class DataSourceConfig {@Bean(name = "primaryDataSource")//命名这个datasource,用来区分不同的bean,比如多个数据库源@Qualifier("primaryDataSource")//@Autowired默认是根据类型进行注入的,因此如果有多个类型一样的Bean候选者,Qualifier则需要限定其中一个候选者,否则将抛出异常,@Qualifier限定描述符除了能根据名字进行注入,更能进行更细粒度的控制如何选择候选者@ConfigurationProperties(prefix="spring.datasource.primary")//读取前缀是什么的配置public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}
}
3.增加JPA配置
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef="entityManagerFactoryPrimary",transactionManagerRef="transactionManagerPrimary",basePackages= { "com.didispace.domain.p" }) //设置Repository所在位置
public class PrimaryConfig {@Autowired @Qualifier("primaryDataSource")private DataSource primaryDataSource;@Primary@Bean(name = "entityManagerPrimary")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryPrimary(builder).getObject().createEntityManager();}@Primary@Bean(name = "entityManagerFactoryPrimary")public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {return builder.dataSource(primaryDataSource).properties(getVendorProperties(primaryDataSource)).packages("com.didispace.domain.p") //设置实体类所在位置.persistenceUnit("primaryPersistenceUnit").build();}@Autowiredprivate JpaProperties jpaProperties;private Map<String, String> getVendorProperties(DataSource dataSource) {return jpaProperties.getHibernateProperties(dataSource);}@Primary@Bean(name = "transactionManagerPrimary")public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());}}
数据源的实体和数据访问对象位于:com.didispace.domain.p
4.在package下创建实体和数据访问接口
@Entity
public class User {@Id@GeneratedValueprivate Long id;@Column(nullable = false)private String name;@Column(nullable = false)private Integer age;public User(){}public User(String name, Integer age) {this.name = name;this.age = age;}// 省略getter、setter}
public interface UserRepository extends JpaRepository<User, Long> {}
至此,JPA配置完成。
使用的时候
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {@Autowiredprivate UserRepository userRepository;@Testpublic void test() throws Exception {userRepository.save(new User("aaa", 10));userRepository.save(new User("bbb", 20));userRepository.save(new User("ccc", 30));userRepository.save(new User("ddd", 40));userRepository.save(new User("eee", 50));Assert.assertEquals(5, userRepository.findAll().size());}}