属性(properties)
这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。
在mybatis配置文件中通过标签可以引入外部properties资源文件,在mybatis配置文件中直接通过${key}引入properties文件的value
-
mybatis-config.xml
<!--加载 config.properties文件 --> <properties resource="config.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments>
-
config.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&serverTimezone=UTC username=root password=123456
-
测试类
@Test public void test1(){ SqlSession session = null; try { session = sqlSessionFactory.openSession(); CountryMapper countryMapper = session.getMapper(CountryMapper.class); List<Country> countries = countryMapper.selectAll(); for (Country country : countries) { System.out.println(country); } } catch (Exception e) { e.printStackTrace(); }finally{ session.close(); } }
-
测试结果
DEBUG [main] - ==> Preparing: select id,countryname,countrycode from country DEBUG [main] - ==> Parameters: DEBUG [main] - <== Total: 5 Country{id=1, countryname='中国', countrycode='CN'} Country{id=2, countryname='美国', countrycode='US'} Country{id=3, countryname='俄罗斯', countrycode='RU'} Country{id=4, countryname='英国', countrycode='GB'} Country{id=5, countryname='法国', countrycode='FR'}