Sql Map配置文件是iBatis配置的核心,从数据库连接到执行SQL时使用的sqlMap文件都是通过此文件中的配置提供给框架的,它通常命名为sqlMapConfig.xml。
一个sqlMapConfig.xml的例子:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <properties resource="resource/connection-configs.properties" /> <settings useStatementNamespaces="true"/> <!-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> <transactionManager type="JDBC" > <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="${driver}"/> <property name="JDBC.ConnectionURL" value="${url}"/> <property name="JDBC.Username" value="${username}"/> <property name="JDBC.Password" value="${password}"/> </dataSource> </transactionManager> <sqlMap resource="resource/sqlMap.xml"/> </sqlMapConfig>
1.<properties>
它在主配置文件外提供一个键/值对应表,是一个properties文件,它可以让sqlmap配置文件更加灵活。上面例子中的connection-configs.properties文件的内容:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/cyh username=root password=root中间的键值就在运行时替换了了下面的<dataSource>元素下的<property>中${driver}等值。
2.<settings>
全局配置选项,有以下属性:
<sqlMap resource="resource/sqlMap1.xml"/> <sqlMap resource="resource/sqlMap2.xml"/> </sqlMapConfig>sqlMap1.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <select id="find_key" resultClass="hashmap"> ...... </select> ......sqlMap2.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <select id="find_key" resultClass="hashmap"> ...... </select> ......
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="com.test.namespace1"> ..... <select id="find_key" resultClass="hashmap"> ...... </select> .....sqlMap2.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="com.test.namespace2"> ..... <select id="find_key" resultClass="hashmap"> ...... </select> .....