动态使用jpa存储库的java分片
我有3个碎片(3个不同的IP、用户名和密码)。我使用SpringBoot,SpringJPA将数据保存在DB中。假设客户是我的实体。让我们假设,基于某个organizationId,我需要插入/更新/选择来自不同数据库的数据。 目前的做法:
@Getter
@Setter
@Entity
@Table
@NoArgsConstructor
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long customerId;
private String firstName;
private String lastName;
private Long organizationId;
}
package lane1;
@Repository
public interface CustomerRepo1 extends CrudRepository<Customer,Long> {
}
package lane2;
@Repository
public interface CustomerRepo2 extends CrudRepository<Customer,Long> {
}
package lane3;
@Repository
public interface CustomerRepo3 extends CrudRepository<Customer,Long> {
}
I am creating 3 datasources(DatasourceLane1, DatasourceLane2, DatasourceLane3) and setting the base packages in the configuration class.
@Configuration
@ConfigurationProperties("DatasourceLane1")
@EnableJpaRepositories(basePackages = "lane1", entityManagerFactoryRef = "lane1EntityManagerFactory",
transactionManagerRef = "lane1TransactionManager")
public class DBConfigurationLane1 {
@NotNull
private String username;
@NotNull
private String password;
@NotNull
private String url;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUrl(String url) {
this.url = url;
}
//@Primary
@Bean
DataSource dataSourceLane1() throws SQLException {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setJdbcUrl(url);
return dataSource;
}
//@Primary
@Bean(name = "lane1EntityManagerFactory")
public EntityManagerFactory propEntityManagerFactory() throws SQLException {
Properties properties = new Properties();
// properties.put("hibernate.hbm2ddl.auto", "update");
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("lane1");
em.setDataSource(dataSourceLane1());
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setPackagesToScan("lane1");
em.setJpaProperties(properties);
em.afterPropertiesSet();
return em.getObject();
}
//@Primary
@Bean(name = "lane1TransactionManager")
public PlatformTransactionManager propTransactionManager(
@Qualifier("lane1EntityManagerFactory") EntityManagerFactory barEntityManagerFactory) {
return new JpaTransactionManager(barEntityManagerFactory);
}
}
类似地,我有datasource2和datasource3
My goal is to have single repository class and dynamically use different datasource based on organizationId.
NOTE : I want to reuse all SimpleJpaRepository(CrudRepository) methods too.
It would be great if someone helps me with code examples. Thank you in advance.
共 (0) 个答案