我需要一个概念来设计一个使用Spring boot,Hibernate和JPA的多数据库应用程序。
现在我考虑支持4种关系数据库(Mysql,H2,SQLLite,Oracle)。
我要做的是使用spring boot profile特性选择正确的数据库配置文件,然后加载相关的数据库属性。
## application-h2.properties
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
# application-mysql.properties
# MySQL-Database
#spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ntk?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect然后在application.properties中
spring.profiles.active=h2在这里,应用程序将运行并加载h2数据库.Same的属性,我们可以选择profile as Mysql,它将加载与Mysql相关的属性。
在这里,大多数情况下,每个查询都是由JPA基于方言生成的。这是兼容所有的数据库(因为,在同一时间,我们正在运行这个应用程序的一个数据库的基础上选择的配置文件).But,我关心的是,如果一些复杂的查询,需要手动编写,我如何才能使它与其他数据库兼容。假设某些为Mysql设计的查询可能与Oracle不兼容。
有没有人可以根据我的描述提出一些建议,如果需要一些其他信息,请让我知道。
发布于 2019-08-10 04:58:01
既然您已经为每个不同的DB定义了不同的配置文件,为什么不创建一个bean来封装所有这些“更高级”的查询,并用@profile对其进行注释,以便根据所选的配置文件实际使用正确的查询呢?
创建一个接口,使用您可能需要的每个高级查询来声明一个方法:
public interface IAdvancedQuery {
void advancedQuery1();
void advancedQuery2();
...
}然后,为每个概要文件创建一个实现此接口的bean,并相应地对其进行注释:
@Profile("h2")
@Component
public class H2Queries implements IAdvancedQuery {
@Override
public void query1() {
// your h2 specific query goes here
}
@Override
public void query2() {
...
}
...
}
@Profile("mysql")
@Component
public class MysqlQueries implements IAdvancedQuery {
@Override
public void query1() {
// your mySQL specific query goes here
}
@Override
public void query2() {
...
}
...
}最后,假设您有一个消费者服务类,您只需使用@Autowired注入适当的bean,根据您在spring应用程序中指定的配置文件自动注入:
@Service
public class ConsumerService {
@Autowired
public IAdvancedQuery advancedQuery;
...
public void someMethod() {
// do something with the advanced query
advancedQuery.query1();
...
}
...
}正确的“高级查询”方法最终将根据配置文件和实例化的bean进行选择。
https://stackoverflow.com/questions/57433420
复制相似问题