java如何跨项目配置多个数据源
我希望围绕静态数据源(从第三方获得)使用Spring Boot和Spring数据(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
}
ItemDao
@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中。然而,由于新项目也使用数据库,所以导入的静态数据jar默认为新项目中配置的数据库。这会导致如下错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxException: Table 'new_project.invtypes' doesn't exist
(这是因为新项目配置为使用“new_project”数据库,以及配置为使用Hibernates改进的命名策略)
一位同事提到在新项目的应用程序中配置这两个数据库。属性-但是我在这种方法上运气不太好。我已经尝试更改spring获取的静态项目的datasource属性的前缀,以便可以配置两个数据库(使用此处的指南:http://xantorohara.blogspot.co.uk/2013/11/spring-boot-jdbc-with-multiple.html),但是这两个项目似乎使用相同的datasource(如果我完全弄错了,我深表歉意)
然后,静态项目的配置变为:
@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以连接到它自己的数据库,而不是作为依赖项包含它的项目的数据库?我是否需要在静态数据项目中执行一些配置,以强制它连接到我决定的数据源
谢谢你的帮助,如果你需要额外的信息,我很乐意提供
# 1 楼答案
在“静态”jar(例如,请参见docs here)中,似乎需要一个自定义实体管理器工厂,以及自定义数据源。拥有自定义实体管理器工厂后,需要声明
@EnableJpaRepositories
,并显式引用实体管理器因子的bean id