轻松实现基本SQL方法:利用BaseMapper类继承编写Mapper文件

        在开发过程中,我们经常需要使用到数据库来存储和管理数据,而Mybatis是一个比较常用的持久层框架。在Mybatis中,我们经常需要编写Mapper文件来与数据库进行交互,然而对于一些非常基础的操作,我们往往需要编写很多重复的SQL语句,这样既费时又费力。本文将介绍一种简单而高效的方法,即通过继承BaseMapper类来实现基本的SQL方法,从而实现Mapper文件中的CRUD操作。

我们只需要在mapper包中创建xxMapper的接口,该接口继承BaseMapper类即可,不需要编写额外的代码,除非你有特殊的数据库操作。

例如:

@Mapper
public interface PlayerMapper extends BaseMapper<Player> {
}

<Player>为实体类对象。

使用时,只需要注入该Mapper对象,通过mapper对象来调用方法即可。

下面的内容了解即可,不用在项目里编写。

BaseMapper类的具体代码为:

public interface BaseMapper<T, ID> {
  long countByExample(Example example);

  int deleteByExample(Example example);

  int deleteByPrimaryKey(ID id);

  int insert(T record);

  int insertSelective(T record);

  List<T> selectByExampleWithBLOBs(Example example);

  List<T> selectByExample(Example example);

  T selectByPrimaryKey(ID id);

  int updateByExampleSelective(@Param("record") T record, @Param("example") Example example);

  int updateByExampleWithBLOBs(@Param("record") T record, @Param("example") Example example);

  int updateByExample(@Param("record") T record, @Param("example") Example example);

  int updateByPrimaryKeySelective(T record);

  int updateByPrimaryKeyWithBLOBs(T record);

  int updateByPrimaryKey(T record);
}
  • countByExample(Example example):统计符合条件的记录数量。
  • deleteByExample(Example example):根据条件删除记录。
  • deleteByPrimaryKey(ID id):根据主键删除记录。
  • insert(T record):插入一条记录。
  • insertSelective(T record):选择性地插入一条记录,可以根据实体类中属性的值插入。
  • selectByExampleWithBLOBs(Example example):根据条件查询符合条件的记录,包含BLOB字段。
  • selectByExample(Example example):根据条件查询符合条件的记录。
  • selectByPrimaryKey(ID id):根据主键查询一条记录。
  • updateByExampleSelective(@Param("record") T record, @Param("example") Example example):根据条件选择性地更新记录,可以根据实体类中属性的值更新。
  • updateByExampleWithBLOBs(@Param("record") T record, @Param("example") Example example):根据条件更新记录,包含BLOB字段。
  • updateByExample(@Param("record") T record, @Param("example") Example example):根据条件更新记录。
  • updateByPrimaryKeySelective(T record):根据主键选择性地更新记录,可以根据实体类中属性的值更新。
  • updateByPrimaryKeyWithBLOBs(T record):根据主键更新记录,包含BLOB字段。
  • updateByPrimaryKey(T record):根据主键更新记录。
  • 返回值为int类型的都是返回成功的记录条数,如果操作失败,则返回0;返回值如果为list或者T的,都是返回查询到的具体内容。

如果你想要操作的方法父类没有,也可以在类里面自己编写。

例如:编写一个查询tb_prize表中id字段的最大值并返回。

@Mapper
public interface PrizeMapper extends BaseMapper<Prize> {
    @Select("SELECT MAX(id) FROM tb_prize")
    Integer selectMaxprizeID();
}

猜你喜欢

转载自blog.csdn.net/weixin_51451545/article/details/131267622