1. 下载依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. 配置多数据源配置信息
#主
spring.datasource.jdbc-url=jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#从
spring.slave.datasource.jdbc-url=jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.slave.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.slave.datasource.username=root
spring.slave.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
注意:
SpringBoot2.x默认使用的数据源是HikariCP
,它使用的连接参数是jdbc-url
而不是url
.
编写数据源配置类
@Configuration
public class DataSourceConfig {
@Bean("master")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
@Bean("slave")
@ConfigurationProperties(prefix = "spring.slave.datasource")
public DataSource dataSourceSlave(){
return DataSourceBuilder.create().build();
}
}
必须有一个@Primary
作为主数据源,生成的@Bean
都将交给Spring
容器进行管理,所以在同类型有多个注册的情况下需要在@Bean
上定义别名,到时候注入的时候可以通过名称来进行注册,以免报错无法注入bean
。
配置数据源的JPA信息
前面的数据源仅仅配置的是一些连接参数,现在我们的JPA需要使用datasource
,所以需要对不同的数据源配置不同的JPA属性。
主:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryMaster",//配置连接工厂 entityManagerFactory
transactionManagerRef = "transactionManagerMaster", //配置事务管理器 transactionManager
basePackages = {"com.ztemap.datasource.repository"}
)
public class MasterDataSourceConfig {
@Autowired
@Qualifier("master")
private DataSource dataSourceMaster;
@Autowired
private JpaProperties jpaProperties;
@Bean("entityManagerMaster")
@Primary
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryBean(builder).getObject().createEntityManager();
}
@Bean("entityManagerFactoryMaster")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
return builder.dataSource(dataSourceMaster)
.properties(getVendorProperties())
.packages("com.ztemap.datasource")
//持久化单元名称,当存在多个EntityManagerFactory时,需要制定此名称
.persistenceUnit("masterPersistenceUnit")
.build();
}
private Map getVendorProperties() {
HibernateSettings hibernateSettings = new HibernateSettings();
// hibernateSettings.ddlAuto(ddlAuto);
return jpaProperties.getHibernateProperties(hibernateSettings);
}
@Bean("transactionManagerMaster")
@Primary
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryBean(builder).getObject());
}
}
从:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySlave",
transactionManagerRef = "transactionManagerSlave",
basePackages = {"com.ztemap.datasource.slave"}
)
public class SlaveDataSourceConfig {
@Autowired
@Qualifier("slave")
private DataSource dataSource;
@Autowired
private JpaProperties jpaProperties;
@Bean("entityManagerFactorySlave")
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
return builder.dataSource(dataSource)
.properties(getVendorProperties())
.packages("com.ztemap.datasource")
.build();
}
@Bean("entityManagerSlave")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return localContainerEntityManagerFactoryBean(builder).getObject().createEntityManager();
}
@Bean("transactionManagerSlave")
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(localContainerEntityManagerFactoryBean(builder).getObject());
}
private Map getVendorProperties() {
HibernateSettings hibernateSettings = new HibernateSettings();
// hibernateSettings.ddlAuto(ddlAuto);
return jpaProperties.getHibernateProperties(hibernateSettings);
}
}
entityManagerFactoryRef映射LocalContainerEntityManagerFactoryBean对应的bean名称,表示配置连接工厂
同理transactionManagerMaster也是一样,表示的是事务管理器
basePackages扫描的是继承JpaRepository<Student,Integer>等类所在的包,packages扫描的是实体类所在的包。
编写数据访问层接口
实体类
@Entity
@Table(name = "t_user")
public class User {
@Id
//主键自动递增
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(length = 20)
private Integer id;
@Column(length = 20)
private String name;
@Column(length = 4)
private Integer age;
@Column(length = 50)
private String addr;
}
数据访问层
public interface UserRepository extends JpaRepository<User,Integer> {
// @Query(value = "select o from User o where id = (select max(id) from User o)" )
@Query(value = "select * from t_user where id = (select max(id) from t_user)",nativeQuery = true)
public User findMaxIdUser();
}