Solve the naming problem of mapper in mybatis

  • 2021-09-12 01:29:16
  • OfStack

mybatis mapper naming problem

In the mapper file, the first letter of id should be lowercase, so as to avoid mybatis thinking that it is a class


    <!-- Get a list of vendors -->
    <resultMap id="ProviderList" type="Provider">
        <result property="id" column="id"/>
        <result property="proCode" column="proCode"/>
        <result property="proName" column="proName"/>
        <result property="proDesc" column="proDesc"/>
        <result property="proContact" column="proContact"/>
        <result property="proPhone" column="proPhone"/>
        <result property="proAddress" column="proAddress"/>
        <result property="creationDate" column="creationDate"/>
    </resultMap>
    <select id="getProviderList" parameterType="Provider" resultMap="ProviderList">
        select * from smbms_provider provider
        where proName like CONCAT('%', #{proName}, '%')
    </select>

The name of id of resultMap is ProviderList, and ProviderList will be understood as a class, which cannot be mapped


    <resultMap id="ProviderList" type="Provider">
        <result property="id" column="id"/>
        <result property="proCode" column="proCode"/>
        <result property="proName" column="proName"/>
        <result property="proDesc" column="proDesc"/>
        <result property="proContact" column="proContact"/>
        <result property="proPhone" column="proPhone"/>
        <result property="proAddress" column="proAddress"/>
        <result property="creationDate" column="creationDate"/>
    </resultMap>

An exception occurs. The correct way to write it is to lowercase the first letter of ProviderList, that is, to avoid problems, the id value in the mapper file is lowercase

Why do you need one name for the interface in Mybatis and the corresponding mapper file?

Background:

I am only in the stage of using Mybatis at this stage, and I still want to have a deep understanding of some problems. Take the interface file of Mybatis and the name of mapper file need 1 to start.

Resolve:

When we put the interface and mapper file in the same package, Mybatis will scan automatically. In this way, we should pay attention to the same name of java interface and mapper file, otherwise an exception will be reported.

At this point we need to configure MapperScannerConfigurer to register all the mappers in the XML configuration file of Spring. Instead, you can use an MapperScannerConfigurer,

It will find the mappers under the classpath and automatically create them as MapperFactoryBean.

To create an MapperScannerConfigurer:


<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  <property name="basePackage" value="com.bijian.study.dao" />  
</bean>  

Related articles: