创建Mapper接口,同时实现BaseMapper类,泛型为对应实体类
添加@Mapper注解
在主启动类上添加@MapperScan注解并添加扫描路径。例:@MapperScan("com.airweb.mapper")
//Mapper接口
@Mapper
public interface AdminMapper extends BaseMapper<Admin> {
}
//主启动类
@MapperScan("com.airweb.mapper")
@MapperScan("com.airweb.listen")
@SpringBootApplication
public class AirWebApplication {
public static void main(String[] args) {
SpringApplication.run(AirWebApplication.class, args);
}
}
到这一步,就可以使用MP中的一些基本的增删改查方法了
只需要在Mapper接口中添加方法,并使用@Select、@Insert、@Delete、@Update等注解写入SQL语句
/**根据Id查找管理员信息中的指定字段BuildingId
*/
@Select("select building_id from admin where admin_id=${id}")
int selectBuildingById(@Param("id")Long adminId);
//其他的增删改也一样,只是注解不同
MybatisPlus其实也有提供一个批量插入的方法,但是那个方式本质上也是多次的调用insert(),所以不用,我们用下面这个insertBatchSomeColumn来实现真正的批量插入
关于 insertBatchSomeColumn(List list) 这个方法,大家可以直接复制下面的代码就可以了
public class InsertBatchSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}
@Component
public class MybatisPlusConfig {
@Bean
public InsertBatchSqlInjector easySqlInjector () {
return new InsertBatchSqlInjector();
}
}
@Mapper
public interface ClassroomMapper extends BaseMapper<Classroom> {
/**
* 批量插入
* @param classrooms
*/
void insertBatchSomeColumn(@Param("list") List<Classroom> classrooms);
}
@Configuration
public class MybatisPlusConfig {
/**
* 批量插入所需要的Bean
* @return
*/
@Bean
public InsertBatchSqlInjector easySqlInjector () {
return new InsertBatchSqlInjector();
}
/**
* 分页插件所需要的Bean
*/
//分页插件
@Bean
public MybatisPlusInterceptor paginationInnerInterceptor(){
MybatisPlusInterceptor paginationInnerInterceptor = new MybatisPlusInterceptor();
paginationInnerInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return paginationInnerInterceptor;
}
}
然后就可以开始使用了,下面是具体操作代码:
//具体操作
//1、创建IPage对象---pageNum为第几页,pageSize为每页几条信息
IPage<Admin> page = new Page<>(pageNum,pageSize);
//调用Mapper接口中的方法
List<Admin> allAdmin = adminMapper.getAllAdmin(page);
//adminMapper接口中的getAllAdmin(page)方法
@Select("select * from admin")
List<Admin> getAllAdmin(IPage<Admin> page);
随机更新
更加详细的信息可以查看MybatisPlus的官网:MybatisPlus,这个还是挺好看懂的!冲!