MybatisPlus_0">MybatisPlus实践积累
文章目录
- MybatisPlus实践积累
- 1.MybatisPlus基础用法(SpringBoot项目中)
- 新建Mapper软件包
- 2.在Mapper中添加自定义方法(单表)
- 3.关于MybatisPlus的批量插入
- 写一个工具类
- 写一个配置类
- 到Mappe中添加这个方法
- 4.关于MybatisPlus中的分页
- 在MybatisPlus的配置类中添加Bean
MybatisPlusSpringBoot_4">1.MybatisPlus基础用法(SpringBoot项目中)
新建Mapper软件包
-
创建Mapper接口,同时实现
BaseMapper<T>
类,泛型为对应实体类 -
添加
@Mapper
注解 -
在主启动类上添加
@MapperScan
注解并添加扫描路径。例:@MapperScan("com.airweb.mapper")
-
java">//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中的一些基本的增删改查方法了
2.在Mapper中添加自定义方法(单表)
只需要在Mapper接口中添加方法,并使用@Select、@Insert、@Delete、@Update
等注解写入SQL语句
java">
/**根据Id查找管理员信息中的指定字段BuildingId
*/
@Select("select building_id from admin where admin_id=${id}")
int selectBuildingById(@Param("id")Long adminId);
//其他的增删改也一样,只是注解不同
MybatisPlus_53">3.关于MybatisPlus的批量插入
MybatisPlus其实也有提供一个批量插入的方法,但是那个方式本质上也是多次的调用insert(),所以不用,我们用下面这个insertBatchSomeColumn来实现真正的批量插入
关于 insertBatchSomeColumn(List list) 这个方法,大家可以直接复制下面的代码就可以了
写一个工具类
java">public class InsertBatchSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}
写一个配置类
java">@Component
public class MybatisPlusConfig {
@Bean
public InsertBatchSqlInjector easySqlInjector () {
return new InsertBatchSqlInjector();
}
}
到Mappe中添加这个方法
java">@Mapper
public interface ClassroomMapper extends BaseMapper<Classroom> {
/**
* 批量插入
* @param classrooms
*/
void insertBatchSomeColumn(@Param("list") List<Classroom> classrooms);
}
MybatisPlus_107">4.关于MybatisPlus中的分页
MybatisPlusBean_109">在MybatisPlus的配置类中添加Bean
java">@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;
}
}
然后就可以开始使用了,下面是具体操作代码:
java">//具体操作
//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,这个还是挺好看懂的!冲!