Spring 数据 JPA 存储库未在多个数据源中获取数据
Spring Data JPA repository not fetching data in multiple datasource
我正在使用 Spring Data JPA,我有 3 个实体和 2 个数据源来获取数据。一个实体连接到一个数据源并通过 JPA 存储库正确获取数据。问题出在第二个实体上。其余两个实体通过每个实体的单独 JPA 存储库连接到 1 个数据源,但只有一个实体在这里工作,而不是另一个。
当我从第二个实体获取数据时,它简单地显示了生成的 sql 并且没有其他错误和结果。有什么我想念的吗?
我的配置文件:
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "orderEntityManagerFactory",
transactionManagerRef = "orderTransactionManager")
public class OrderConfig {
@Value("${spring.datasource.driver-class-name}")
private String driverClass;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password-key}")
private String passwordKey;
@Value("${spring.datasource.password-encrypted}")
private String passwordEncrypted;
@Bean
PlatformTransactionManager orderTransactionManager() {
return new JpaTransactionManager(orderEntityManagerFactory().getObject());
}
@Primary
@PersistenceContext(unitName = "first")
@Bean(name = "orderEntityManagerFactory")
LocalContainerEntityManagerFactoryBean orderEntityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(orderDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan(OrderConfig.class.getPackage().getName());
return factoryBean;
}
@Bean(name = "orderDataSource")
@Primary
public DataSource orderDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setJdbcUrl(url);
dataSource.setUsername(username);
dataSource.setMaximumPoolSize(2);
dataSource.setPassword(AESCryption.decrypt(passwordKey, passwordEncrypted));
return dataSource;
}
另一个配置文件:
public class BoardRateConfig {
@Value("${spring.datasource.driver-class-name-oracle}")
private String driverClass;
@Value("${spring.datasource.url-oracle}")
private String url;
@Value("${spring.datasource.username-oracle}")
private String username;
@Value("${spring.datasource.password-key-oracle}")
private String passwordKey;
@Value("${spring.datasource.password-encrypted-oracle}")
private String passwordEncrypted;
@Bean
PlatformTransactionManager boardRateTransactionManager() {
return new JpaTransactionManager(boardRateEntityManagerFactory().getObject());
}
@PersistenceContext(unitName = "second")
@Bean(name = "boardRateEntityManagerFactory")
LocalContainerEntityManagerFactoryBean boardRateEntityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(boardRateDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan(BoardRateConfig.class.getPackage().getName());
return factoryBean;
}
@Bean(name = "boardRateDataSource")
public DataSource boardRateDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setJdbcUrl(url);
dataSource.setUsername(username);
dataSource.setMaximumPoolSize(2);
dataSource.setPassword(AESCryption.decrypt(passwordKey, passwordEncrypted));
return dataSource;
}
我的实体:
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = {"orderId"})
@Entity
@Table(name = "customer_order", uniqueConstraints = { @UniqueConstraint(columnNames = { "transaction_id", "region" }) })
@Data
public class Order {
@Id
@GeneratedValue
@Column(name = "order_id", columnDefinition="Unique Identifier of the Order")
private Long orderId;
@Column(name = "source_system")
private String sourceSystem;
@NotNull
@Column(name = "region", nullable = false)
@Enumerated(EnumType.STRING)
private Region region;
@NotNull
@Column(name = "transaction_id", nullable = false)
private String transactionId;
@NotNull
@Column(name = "dealt_currency", nullable = false)
private String dealtCurrency;
@NotNull
@Column(name = "currency_pair", nullable = false)
private String currencyPair;
@Column(name = "dealth_amount", nullable = false)
private BigDecimal dealtAmount;
@NotNull
@Column(name = "expected_rate", nullable = false)
private BigDecimal expectedRate;
@Column(name = "matched_rate", nullable = false)
private BigDecimal matchedRate;
@NotNull
@Column(name = "request_type", nullable = false)
@Enumerated(EnumType.STRING)
private RequestType requestType;
@NotNull
@Column(name = "status", nullable = false)
@Enumerated(EnumType.STRING)
private Status status;
@GridColumn(caption="Expiry Date (SGT)")
@Column(name = "expiry_date")
private LocalDateTime expiryDate;
@GridColumn(caption="Created Date (SGT)")
@Column(name = "created_date")
private LocalDateTime createdDate;
@GridColumn(caption="Matched Date Time (SGT)")
@Column(name = "matched_date_time")
private LocalDateTime matchedDateTime;
@GridColumn(caption="Updated Date (SGT)")
@Column(name = "updated_date")
private LocalDateTime updatedDate;
@GridColumn(caption="Expired Date Time (SGT)")
@Column(name = "expired_date_time")
private LocalDateTime expiredDateTime;
@Column(name = "price_tier")
private String priceTier;
@NotNull
@Column(name = "price_tier_currency", nullable = false)
private String priceTierCurrency;
@Version
private Integer version;
@Size(max = 1)
@Column(name = "service_type")
private String serviceType;
public static enum Status {
PENDING, MATCHED, EXPIRED, DELETED, NOTIFIED, ACKNOWLEDGED;
}
public static String getStatusValue(Status value){
if(value == Status.ACKNOWLEDGED)
return "ACKNOWLEDGED";
if(value == Status.MATCHED)
return "MATCHED";
if(value == Status.EXPIRED)
return "EXPIRED";
if(value == Status.DELETED)
return "DELETED";
if(value == Status.NOTIFIED)
return "NOTIFIED";
if(value == Status.PENDING)
return "PENDING";
return null;
}
public static Stream<Status> statusStream(){
return Arrays.stream(Status.values());
}
public static enum RequestType {
BUY, SELL;
}
public static String getRequestTypeValue(RequestType value){
if(value.equals(RequestType.BUY)){
return "BUY";
} else {
return "SELL";
}
}
}
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "orderId")
@Entity
@Table(name = "orders_match_at_board_rate_timestamp", uniqueConstraints = { @UniqueConstraint(columnNames = { "board_rate_timestamp", "order_id" }) })
public class BoardRateTimeStamp {
@Id
@GeneratedValue
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "board_rate_timestamp", nullable = false)
private LocalDateTime boardRateTimestamp;
@Column(name = "order_id", columnDefinition="Unique Identifier of the Order")
private Long orderId;
}
存储库:
public interface BoardRateTimeStampRepository extends JpaRepository<BoardRateTimeStamp, Long> {
@Query("SELECT brt FROM BoardRateTimeStamp brt WHERE brt.orderId IS NOT NULL AND brt.boardRateTimestamp >= :fromDate AND brt.boardRateTimestamp <= :toDate ")
List<BoardRateTimeStamp> findMatchedOrdersBoardRateTimeStampListBetweenDateRange(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate);
}
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("SELECT o FROM Order o WHERE o.createdDate >= :fromDate AND o.createdDate <= :toDate")
public List<Order> findOrderBetweenDateRangeForCreatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate);
@Query("SELECT o FROM Order o WHERE o.createdDate >= :fromDate AND o.createdDate <= :toDate AND o.status IN ( :status )")
public List<Order> findOrderBetweenDateRangeForStatusForCreatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate, @Param("status") EnumSet<Order.Status> status);
@Query("SELECT o FROM Order o WHERE o.updatedDate >= :fromDate AND o.updatedDate <= :toDate")
public List<Order> findOrderBetweenDateRangeForUpdatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate);
@Query("SELECT o FROM Order o WHERE o.updatedDate >= :fromDate AND o.updatedDate <= :toDate AND o.status IN ( :status )")
public List<Order> findOrderBetweenDateRangeForStatusForUpdatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate, @Param("status") EnumSet<Order.Status> status);
@Query("SELECT o FROM Order o WHERE o.createdDate >= :date")
public List<Order> findOrdersCreatedToday(@Param("date") LocalDateTime date);
@Query("SELECT o FROM Order o WHERE o.updatedDate >= :date")
public List<Order> findOrdersUpdatedToday(@Param("date") LocalDateTime date);
@Query("SELECT o FROM Order o WHERE o.status = 'PENDING' ORDER BY o.currencyPair, o.priceTier ")
public List<Order> findAllPendingOrders();
public interface BoardRateRepository extends JpaRepository<BoardRate, BigInteger> {
@Query("SELECT br FROM BoardRate br WHERE br.rateTypeId = 2 ORDER BY br.baseCurrency || br.quoteCurrency, br.regionTierId")
public List<BoardRate> findLatestBoardRates();
}
此处 BoardRateRepository 和 OrderRepository 工作正常,但 BoardRateTimeStampRepository 不工作。
当我调用 boardRateTimeStampRepository.findAll()
时,我得到的是空列表。
我没有在上面的代码中包含包的详细信息,但是存储库完全在不同的包中,所以上面的代码工作正常。
此外,这个问题是由于最愚蠢的原因造成的。我为导致此问题的每个数据源指向不同的环境。我将其指向正确的环境并且一切正常!!
无论如何谢谢!!
我正在使用 Spring Data JPA,我有 3 个实体和 2 个数据源来获取数据。一个实体连接到一个数据源并通过 JPA 存储库正确获取数据。问题出在第二个实体上。其余两个实体通过每个实体的单独 JPA 存储库连接到 1 个数据源,但只有一个实体在这里工作,而不是另一个。
当我从第二个实体获取数据时,它简单地显示了生成的 sql 并且没有其他错误和结果。有什么我想念的吗?
我的配置文件:
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "orderEntityManagerFactory",
transactionManagerRef = "orderTransactionManager")
public class OrderConfig {
@Value("${spring.datasource.driver-class-name}")
private String driverClass;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password-key}")
private String passwordKey;
@Value("${spring.datasource.password-encrypted}")
private String passwordEncrypted;
@Bean
PlatformTransactionManager orderTransactionManager() {
return new JpaTransactionManager(orderEntityManagerFactory().getObject());
}
@Primary
@PersistenceContext(unitName = "first")
@Bean(name = "orderEntityManagerFactory")
LocalContainerEntityManagerFactoryBean orderEntityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(orderDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan(OrderConfig.class.getPackage().getName());
return factoryBean;
}
@Bean(name = "orderDataSource")
@Primary
public DataSource orderDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setJdbcUrl(url);
dataSource.setUsername(username);
dataSource.setMaximumPoolSize(2);
dataSource.setPassword(AESCryption.decrypt(passwordKey, passwordEncrypted));
return dataSource;
}
另一个配置文件:
public class BoardRateConfig {
@Value("${spring.datasource.driver-class-name-oracle}")
private String driverClass;
@Value("${spring.datasource.url-oracle}")
private String url;
@Value("${spring.datasource.username-oracle}")
private String username;
@Value("${spring.datasource.password-key-oracle}")
private String passwordKey;
@Value("${spring.datasource.password-encrypted-oracle}")
private String passwordEncrypted;
@Bean
PlatformTransactionManager boardRateTransactionManager() {
return new JpaTransactionManager(boardRateEntityManagerFactory().getObject());
}
@PersistenceContext(unitName = "second")
@Bean(name = "boardRateEntityManagerFactory")
LocalContainerEntityManagerFactoryBean boardRateEntityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(boardRateDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan(BoardRateConfig.class.getPackage().getName());
return factoryBean;
}
@Bean(name = "boardRateDataSource")
public DataSource boardRateDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setJdbcUrl(url);
dataSource.setUsername(username);
dataSource.setMaximumPoolSize(2);
dataSource.setPassword(AESCryption.decrypt(passwordKey, passwordEncrypted));
return dataSource;
}
我的实体:
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = {"orderId"})
@Entity
@Table(name = "customer_order", uniqueConstraints = { @UniqueConstraint(columnNames = { "transaction_id", "region" }) })
@Data
public class Order {
@Id
@GeneratedValue
@Column(name = "order_id", columnDefinition="Unique Identifier of the Order")
private Long orderId;
@Column(name = "source_system")
private String sourceSystem;
@NotNull
@Column(name = "region", nullable = false)
@Enumerated(EnumType.STRING)
private Region region;
@NotNull
@Column(name = "transaction_id", nullable = false)
private String transactionId;
@NotNull
@Column(name = "dealt_currency", nullable = false)
private String dealtCurrency;
@NotNull
@Column(name = "currency_pair", nullable = false)
private String currencyPair;
@Column(name = "dealth_amount", nullable = false)
private BigDecimal dealtAmount;
@NotNull
@Column(name = "expected_rate", nullable = false)
private BigDecimal expectedRate;
@Column(name = "matched_rate", nullable = false)
private BigDecimal matchedRate;
@NotNull
@Column(name = "request_type", nullable = false)
@Enumerated(EnumType.STRING)
private RequestType requestType;
@NotNull
@Column(name = "status", nullable = false)
@Enumerated(EnumType.STRING)
private Status status;
@GridColumn(caption="Expiry Date (SGT)")
@Column(name = "expiry_date")
private LocalDateTime expiryDate;
@GridColumn(caption="Created Date (SGT)")
@Column(name = "created_date")
private LocalDateTime createdDate;
@GridColumn(caption="Matched Date Time (SGT)")
@Column(name = "matched_date_time")
private LocalDateTime matchedDateTime;
@GridColumn(caption="Updated Date (SGT)")
@Column(name = "updated_date")
private LocalDateTime updatedDate;
@GridColumn(caption="Expired Date Time (SGT)")
@Column(name = "expired_date_time")
private LocalDateTime expiredDateTime;
@Column(name = "price_tier")
private String priceTier;
@NotNull
@Column(name = "price_tier_currency", nullable = false)
private String priceTierCurrency;
@Version
private Integer version;
@Size(max = 1)
@Column(name = "service_type")
private String serviceType;
public static enum Status {
PENDING, MATCHED, EXPIRED, DELETED, NOTIFIED, ACKNOWLEDGED;
}
public static String getStatusValue(Status value){
if(value == Status.ACKNOWLEDGED)
return "ACKNOWLEDGED";
if(value == Status.MATCHED)
return "MATCHED";
if(value == Status.EXPIRED)
return "EXPIRED";
if(value == Status.DELETED)
return "DELETED";
if(value == Status.NOTIFIED)
return "NOTIFIED";
if(value == Status.PENDING)
return "PENDING";
return null;
}
public static Stream<Status> statusStream(){
return Arrays.stream(Status.values());
}
public static enum RequestType {
BUY, SELL;
}
public static String getRequestTypeValue(RequestType value){
if(value.equals(RequestType.BUY)){
return "BUY";
} else {
return "SELL";
}
}
}
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "orderId")
@Entity
@Table(name = "orders_match_at_board_rate_timestamp", uniqueConstraints = { @UniqueConstraint(columnNames = { "board_rate_timestamp", "order_id" }) })
public class BoardRateTimeStamp {
@Id
@GeneratedValue
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "board_rate_timestamp", nullable = false)
private LocalDateTime boardRateTimestamp;
@Column(name = "order_id", columnDefinition="Unique Identifier of the Order")
private Long orderId;
}
存储库:
public interface BoardRateTimeStampRepository extends JpaRepository<BoardRateTimeStamp, Long> {
@Query("SELECT brt FROM BoardRateTimeStamp brt WHERE brt.orderId IS NOT NULL AND brt.boardRateTimestamp >= :fromDate AND brt.boardRateTimestamp <= :toDate ")
List<BoardRateTimeStamp> findMatchedOrdersBoardRateTimeStampListBetweenDateRange(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate);
}
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("SELECT o FROM Order o WHERE o.createdDate >= :fromDate AND o.createdDate <= :toDate")
public List<Order> findOrderBetweenDateRangeForCreatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate);
@Query("SELECT o FROM Order o WHERE o.createdDate >= :fromDate AND o.createdDate <= :toDate AND o.status IN ( :status )")
public List<Order> findOrderBetweenDateRangeForStatusForCreatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate, @Param("status") EnumSet<Order.Status> status);
@Query("SELECT o FROM Order o WHERE o.updatedDate >= :fromDate AND o.updatedDate <= :toDate")
public List<Order> findOrderBetweenDateRangeForUpdatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate);
@Query("SELECT o FROM Order o WHERE o.updatedDate >= :fromDate AND o.updatedDate <= :toDate AND o.status IN ( :status )")
public List<Order> findOrderBetweenDateRangeForStatusForUpdatedDate(@Param("fromDate") LocalDateTime fromDate, @Param("toDate") LocalDateTime toDate, @Param("status") EnumSet<Order.Status> status);
@Query("SELECT o FROM Order o WHERE o.createdDate >= :date")
public List<Order> findOrdersCreatedToday(@Param("date") LocalDateTime date);
@Query("SELECT o FROM Order o WHERE o.updatedDate >= :date")
public List<Order> findOrdersUpdatedToday(@Param("date") LocalDateTime date);
@Query("SELECT o FROM Order o WHERE o.status = 'PENDING' ORDER BY o.currencyPair, o.priceTier ")
public List<Order> findAllPendingOrders();
public interface BoardRateRepository extends JpaRepository<BoardRate, BigInteger> {
@Query("SELECT br FROM BoardRate br WHERE br.rateTypeId = 2 ORDER BY br.baseCurrency || br.quoteCurrency, br.regionTierId")
public List<BoardRate> findLatestBoardRates();
}
此处 BoardRateRepository 和 OrderRepository 工作正常,但 BoardRateTimeStampRepository 不工作。
当我调用 boardRateTimeStampRepository.findAll()
时,我得到的是空列表。
我没有在上面的代码中包含包的详细信息,但是存储库完全在不同的包中,所以上面的代码工作正常。
此外,这个问题是由于最愚蠢的原因造成的。我为导致此问题的每个数据源指向不同的环境。我将其指向正确的环境并且一切正常!!
无论如何谢谢!!