Using configuration.xml file and supplying DataSource settings in MyBatis 3.0.6
MyBatis documentation shows a way to build a SqlSessionFactory
through XML configuration file or a Configuration
object through Java code. It also mentions passing properties that will override what is specified in the XML file.
I am trying use the properties facility to supply a data source开发者_如何学C URL in addition to the XML configuration, but the property does not get set.
Here's the configuration XML I am using (removed all the aliases and mappings for brevity):
<configuration>
<typeAliases>
<typeAlias alias="Item" type="com.example.project.Item"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:C:/path_to_db_file_in_the_filesystem"/>
<property name="username" value="sa"/>
<property name="password" value="sa"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/project/mappers/ItemMapper.xml"/>
</mappers>
</configuration>
The XML file works fine for everything, but I need to supply the url
through Java code (through the code, it is obtained from another configuration file so it has to be dynamically supplied to MyBatis). I know I can do it all in code, but that will be unnecessary work so I would like to avoid that route if possible.
Based on the description in the manual, I removed the url
line from the XML file and came up with the following code:
String resource = "com/example/project/MyBatisConfiguration.xml";
Reader reader = Resources.getResourceAsReader(resource);
Properties props = new Properties();
props.setProperty("url", url);
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader, props);
The code builds the SqlSessionFactory
, but I get the "url cannot be null" exception, indicating that the property was not successfully overwritten. I think the name of the property should be in a special format, but I could not find out what that format is.
Thanks a lot in advance for all the help.
In your configuration XML you can insert a placeholder for the datasource URL like that:
<property name="url" value="${url}"/>
Then the build()
method of SqlSessionFactoryBuilder
replaces "${url}"
in the XML with the value of property "url"
provided by props
.
精彩评论