在平時的工作中有時候是需要在配置文件中配置全局變量的,因為這些東西是不會變的,並且每個mapper都傳參的話也顯得有點繁瑣,還好mybatis本身是支持全局變量的,今天工作中用到了,記錄一下。
先在實例化sqlSessionFactory的時候添加上mybatis-configuration.xml的配置文件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:mapping/*.xml" /> <property name="configLocation" value="classpath:mybatis-configuration.xml" /> </bean>
之后在mybatis-configuration配置文件中添加全局變量
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties> <property name="變量名" value="變量的值"/> </properties> </configuration>
之后就可以在任何一個mybatis中使用這個全局變量了。
<select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String" > select u.id, u.userName from ${變量名}.Manage u where u.userName = #{userName,jdbcType=VARCHAR} </select>