簡體   English   中英

如何跨項目配置多個數據源

[英]How to configure multiple datasources across projects

我正在尋找使用Spring Boot和Spring Data(RELEASE 1.1.3)圍繞靜態數據源(從第三方獲得)構建一個應用程序,該應用程序將圍繞上述數據有效地提供API,從中我可以構建一個前端,但也可以作為依賴項包含在其他項目中(以提供對靜態數據的訪問權限),我已經使用@RepositoryRestResource批注設法實現了API部分,但是卻為后者而苦惱。

示例類: 項目實體

@Entity
@Table(name = "invTypes")
public class Item {


  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "typeID", nullable = false)
  private int id;

  @Column(name = "typeName")
  private String name;

  //Remainder ommitted
}

項道

@RepositoryRestResource(collectionResourceRel = "items", path = "items")
public interface ItemDao extends PagingAndSortingRepository<Item, Integer> {

  Item findById(@Param("id") int id);

  Item findByName(@Param("name") String name);

  List<Item> findByNameContains(@Param("name") String name);
}

基本上,我想將其打包為jar以便在另一個項目中使用,這樣我就可以配置2個數據庫(一個是靜態數據源,另一個與新項目相關)

我已經設法打包了靜態數據項目並將其作為依賴項包含在另一個pom.xml中,但是由於新項目還使用數據庫,因此導入的靜態數據jar默認為新項目中配置的數據庫。 這將導致如下錯誤:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxException: Table 'new_project.invtypes' doesn't exist

(這是因為新項目配置為使用“ new_project”數據庫,並且配置為使用Hibernates ImprovementNamingStrategy)

一位同事提到在新項目的application.properties中配置這兩個數據庫-但是我對這種方法不太滿意。 我試過更改spring所拾取的靜態項目的數據源屬性的前綴,以便可以配置兩個數據庫(使用此處的指南: http : //xantorohara.blogspot.co.uk/2013/11/ spring-boot-jdbc-with-multiple.html ),但是,這兩個項目似乎都使用相同的數據源(如果我全都錯了,我表示歉意)

靜態項目的配置隨后變為:

@Configuration
@ConfigurationProperties(prefix = "spring.ds_static")
class DataSourceConfig extends TomcatDataSourceConfiguration {
  @Bean(name = "dsStatic")
  public DataSource dataSource() {
    return super.dataSource();
  }

  @Bean(name = "jdbcStatic")
  public JdbcTemplate jdbcTemplate(DataSource dsStatic) {
    return new JdbcTemplate(dsStatic);
  }
}

上面方法的屬性最終變成了,但是導致了與以前相同的錯誤:

# Configured properties for the new project
spring.datasource.url=jdbc:mysql://localhost/new_projct
spring.datasource.username=dbuser
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy

# Configured properties for the static data jar
spring.ds_static.url=jdbc:mysql://localhost/static_data
spring.ds_static.username=dbuser
spring.ds_static.password=password
spring.ds_static.driverClassName=com.mysql.jdbc.Driver

如何包含和配置jar以連接到其自己的數據庫,而不是將依賴項包含在其中的項目數據庫? 我是否需要在靜態數據項目中執行一些配置以強制其連接到我決定的數據源?

感謝您的幫助,如果您需要其他信息,我們將很樂意為您提供幫助

看來您需要在“靜態” jar中的自定義實體管理器工廠(例如,請參閱此處的文檔 ),以及自定義數據源。 擁有自定義實體管理器工廠后,需要聲明@EnableJpaRepositories並顯式引用您的實體管理器因子的bean ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM