Spring Data JPA存储库不在多个数据源中获取数据

时间:2017-11-21 08:56:47

标签: hibernate spring-boot spring-data-jpa multiple-databases

我正在使用Spring Data JPA,我有3个实体和2个数据源来获取数据。一个实体连接到一个数据源并通过JPA Repository正确获取数据。问题出在第二个实体上。剩余的两个实体通过单独的JPA Repository连接到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()时,我会收到空​​列表。

1 个答案:

答案 0 :(得分:0)

我没有在上面的代码中包含软件包详细信息,但是存储库完全在不同的软件包中,所以上面的代码工作正常。

此外,问题是由于最愚蠢的原因。我指的是导致这个问题的每个数据源的不同环境。我把它指向了正确的环境并且工作得很好!!

非常感谢!!