Issue
I'm using SpringBoot and MyBatis (using mapper XML) to build an application. Assume there's such a query:
SELECT ... FROM some_database.some_table WHERE ...
in which some_database
could change in different "environments" (like project
or project_cloud
). By this time, to build artifacts for different "environments", we have to grep
in our XML files. I wonder if there's a best practice to such circumstance.
AFAIK, for JPA, one may configure data sources with application.yml
so that they may refer to "databases" with data source names, instead of actual data base names. I wonder if there's such an option for MyBatis.
Solution
The proper way to achieve this is by using MyBatis configuration properties (https://mybatis.org/mybatis-3/configuration.html#properties), e.g.
application.yml
mybatis:
...
configuration-properties:
dbschema: project
application-cloud.yml
mybatis:
...
configuration-properties:
dbschema: project_cloud
SomeMapper.xml
...
<select id="getWhateverById" resultMap="...">
select ...
from ${dbschema}.some_table
where ...
</select>
The configuration in application.yml
will be active by default while application-cloud.yml
will override it when the app is run with the cloud
profile active.
Make sure to have the org.mybatis.spring.boot:mybatis-spring-boot-starter
dependency in your project (https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/).
Answered By - dekkard
Answer Checked By - Senaida (JavaFixing Volunteer)