使用mybatis 通用Mapper类的笔记

  • Post author:
  • Post category:其他


想要偷懒不写mybatis里的一大堆mapper.xml文件,就想使用通用的Mapper类减少工作量。

首先,我使用的是Maven项目,所以导入Mapper的Maven依赖



  1. <


    dependency


    >





  2. <


    groupId


    >


    tk.mybatis


    </


    groupId


    >





  3. <


    artifactId


    >


    mapper


    </


    artifactId


    >





  4. <


    version


    >


    3.2.0


    </


    version


    >





  5. </


    dependency


    >




同时有一项必要依赖项:项目依赖于JPA的注解,需要添加Maven依赖:




  1. <


    dependency


    >





  2. <


    groupId


    >


    javax.persistence


    </


    groupId


    >





  3. <


    artifactId


    >


    persistence-api


    </


    artifactId


    >





  4. <


    version


    >


    1.0


    </


    version


    >





  5. </


    dependency


    >




接下来,在配置文件applicationContext.xml中配置Mapper



  1. <


    bean




    class


    =


    “tk.mybatis.spring.mapper.MapperScannerConfigurer”


    >





  2. <


    property




    name


    =


    “basePackage”




    value


    =


    “com.isscas.ucqcs.common.dao”


    />





  3. <


    property




    name


    =


    “properties”


    >





  4. <


    value


    >





  5. mappers


    =


    tk


    .mybatis.mapper.common.Mapper      //这是Mapper接口配置,当接口为此默认配置时,可不写



  6. </


    value


    >





  7. </


    property


    >





  8. </


    bean


    >




直接将MyBatis的配置 org 修改为 tk 即可




  1. <


    bean




    class


    =


    “org.mybatis.spring.mapper.MapperScannerConfigurer”


    >




到这里,Mapper的配置已经全部完成。


只要在自己的Mapper接口上继承Mapper<T>接口,即可调用通用Mapper类中全部的方法。



另外要注意的是


:该Mapper类对实体类有自己的解析方式  :  表名和字段名会默认使用类名,驼峰转下划线(即UserNamed对应表名/字段名user_name),使用

@Column(name = “真实名称”)

可以指定表名/字段名。



另,需要

@Id

标记主键字段,对不需要的字段,可用

@Tranisent

忽略


Mapper接口中包含单表的增删改查分页功能。

下面给出一个查询实例:



  1. CountryMapper


    mapper


    =


    sqlSession


    .getMapper(CountryMapper.class);


  2. //查询全部

  3. List

    <


    Country


    >




    countryList


    =


    mapper


    .select(new Country());


  4. //总数


  5. //通用Example查询

  6. Example

    example


    =


    new


    Example(Country.class);


  7. example.createCriteria().andGreaterThan(“id”, 100);//这里给出的条件查询为id

    >


    100



  8. countryList


    =


    mapper


    .selectByExample(example);