Search code examples
javaspringmybatisspring-mybatis

Access Variable value in Mapper File of mybatis


I am using Spring and Mybatis in my project . Project can run in any platform like SQL Server Oracle etc.

I am facing 1 Problem i want to access variable value From properties file,application Context file to Mybatis Mapper file.

For.eg : ApplicationContext.xml - Spring file
config.properties file

in above file want to decalare variable lets say
pName = XYZ

i want to access this pName in Mybatis Mapper XML file.

<select id="getValue" parameterType="java.lang.String" >
${pName}
</select>

How is it possible ?if have any other solution most welcome.


Solution

  • To access spring way : Use

    <util:properties id="myPropertyConfigurer" location="classpath:yourpropertiesfile.properties"/>
    
    <context:property-placeholder  properties-ref="myPropertyConfigurer" order="1" ignore-unresolvable="true" />
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="applicationDataSource" />
        <property name="configLocation" value="classpath:sqlMapConfig.xml" />
        <property name="configurationProperties" ref="myPropertyConfigurer"></property>
    </bean>
    

    In your mapper xml file :

    <select id="searchSomeOne" parameterType="map" .....>
            SELECT
            ${pName} AS module
            FROM MY_TABLE
            WHERE
            COL_ONE = #{moduleName} and
            COL_TWO like #{username}
    </select>
    

    and define pName=MODULE in the yourpropertiesfile.properties