最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

MybatisPlus不好用,帥小伙一氣之下寫了個MybatisPlusPro

2023-06-18 14:50 作者:流浪在銀河邊緣的阿強(qiáng)  | 我要投稿

富貴同學(xué)在用MybatisPlus作為開發(fā)的時候,雖然好用,但是大多數(shù)都在對dao層面的增刪改查,所以打算自己抽取一套在controller層的功能出來,先介紹一下,“MybatisPlusPro” :只要繼承一個BaseController類,就可以擁有增刪改查,查詢列表,分頁查詢,排序,帶參數(shù)查詢,統(tǒng)計數(shù)量。話不多說,直接開始吧!

第一步,引入MybatisPlus的jar包

java復(fù)制代碼 ? <dependency> ?? ? ? ? ? ?<groupId>com.baomidou</groupId> ?? ? ? ? ? ?<artifactId>mybatis-plus-boot-starter</artifactId> ?? ? ? ? ? ?<version>3.4.2</version> ?? ? ? ?</dependency>

第二步,編寫util類

java復(fù)制代碼import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; ?import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; ?/** ?* Apprentice系統(tǒng)Util ?* ?* @author MaSiyi ?* @version 1.0.0 2021/11/26 ?* @since JDK 1.8.0 ?*/ public class ApprenticeUtil { ? ? ?private static Pattern humpPattern = Pattern.compile("[A-Z]"); ?? ?private static Pattern linePattern = Pattern.compile("_(\\w)"); ? ? ?/** ?? ? * 駝峰轉(zhuǎn)下劃線 ?? ? * ?? ? * @Param: [str] ?? ? * @return: java.lang.String ?? ? * @Author: MaSiyi ?? ? * @Date: 2021/11/26 ?? ? */ ?? ?public static String humpToLine(String str) { ?? ? ? ?Matcher matcher = humpPattern.matcher(str); ?? ? ? ?StringBuffer sb = new StringBuffer(); ?? ? ? ?while (matcher.find()) { ?? ? ? ? ? ?matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase()); ?? ? ? ?} ?? ? ? ?matcher.appendTail(sb); ?? ? ? ?return sb.toString(); ?? ?} ? ? ?/** ?? ? * 下劃線轉(zhuǎn)駝峰 ?? ? * ?? ? * @Param: [str] ?? ? * @return: java.lang.String ?? ? * @Author: MaSiyi ?? ? * @Date: 2021/11/26 ?? ? */ ?? ?public static String lineToHump(String str) { ?? ? ? ?str = str.toLowerCase(); ?? ? ? ?Matcher matcher = linePattern.matcher(str); ?? ? ? ?StringBuffer sb = new StringBuffer(); ?? ? ? ?while (matcher.find()) { ?? ? ? ? ? ?matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); ?? ? ? ?} ?? ? ? ?matcher.appendTail(sb); ?? ? ? ?return sb.toString(); ?? ?} ? ? ?/** ?? ? * 獲取QueryWrapper ?? ? * ?? ? * @Param: [entity] ?? ? * @return: com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<E> ?? ? * @Author: MaSiyi ?? ? * @Date: 2021/11/26 ?? ? */ ?? ?public static <E> QueryWrapper<E> getQueryWrapper(E entity) { ?? ? ? ?Field[] fields = entity.getClass().getDeclaredFields(); ?? ? ? ?QueryWrapper<E> eQueryWrapper = new QueryWrapper<>(); ?? ? ? ?for (int i = 0; i < fields.length; i++) { ?? ? ? ? ? ?Field field = fields[i]; ?? ? ? ? ? ?//忽略final字段 ?? ? ? ? ? ?if (Modifier.isFinal(field.getModifiers())) { ?? ? ? ? ? ? ? ?continue; ?? ? ? ? ? ?} ?? ? ? ? ? ?field.setAccessible(true); ?? ? ? ? ? ?try { ?? ? ? ? ? ? ? ?Object obj = field.get(entity); ?? ? ? ? ? ? ? ?if (!ObjectUtils.isEmpty(obj)) { ?? ? ? ? ? ? ? ? ? ?String name = ApprenticeUtil.humpToLine(field.getName()); ?? ? ? ? ? ? ? ? ? ?eQueryWrapper.eq(name, obj); ?? ? ? ? ? ? ? ?} ?? ? ? ? ? ?} catch (IllegalAccessException e) { ?? ? ? ? ? ? ? ?return null; ?? ? ? ? ? ?} ?? ? ? ?} ?? ? ? ?return eQueryWrapper; ? ? ?} ? ? ?/** 反射獲取字段值 ?? ? * @Param: [entity, value] value 值為 "id" "name" 等 ?? ? * @return: java.lang.Object ?? ? * @Author: MaSiyi ?? ? * @Date: 2021/11/26 ?? ? */ ?? ?public static <E> Object getValueForClass(E entity,String value) { ? ? ? ? ?Field id = null; ?? ? ? ?PropertyDescriptor pd = null; ?? ? ? ?try { ?? ? ? ? ? ?id = entity.getClass().getDeclaredField(value); ?? ? ? ? ? ?pd = new PropertyDescriptor(id.getName(), entity.getClass()); ?? ? ? ?} catch (NoSuchFieldException | IntrospectionException e) { ?? ? ? ? ? ?e.printStackTrace(); ?? ? ? ?} ?? ? ? ?//獲取get方法 ?? ? ? ?Method getMethod = Objects.requireNonNull(pd).getReadMethod(); ?? ? ? ?return ReflectionUtils.invokeMethod(getMethod, entity); ?? ?} } ?

反射獲取字段值,這段Java代碼演示了如何使用反射獲得指定對象的屬性值。方法的泛型表示,可以接受任意類型的參數(shù)entity。在此代碼中,首先通過反射獲取參數(shù)entity對象所對應(yīng)類的屬性,即value

接著通過Java內(nèi)置的Introspector機(jī)制獲取id屬性的JavaBean規(guī)范訪問器PropertyDescriptor,并從該對象提取出對應(yīng)的getter方法。最后,利用Spring框架提供的工具類ReflectionUtils得到方法后來調(diào)用該getter方法,獲取屬性值并返回。需要注意,在反射機(jī)制下如果要訪問私有成員變量或方法時,應(yīng)先調(diào)用其setAccessible(true)方法以獲得權(quán)限。

第三步,我們編寫B(tài)aseController類

下面是我們的BaseController類

java復(fù)制代碼 import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import com.wangfugui.apprentice.common.util.ApprenticeUtil; import com.wangfugui.apprentice.common.util.ResponseUtils; import com.wangfugui.apprentice.dao.dto.PageParamDto; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; ?import java.util.List; ?/** 核心公共controller類 ?* @Param: ?* @return: ?* @Author: MaSiyi ?* @Date: 2021/11/26 ?*/ public class BaseController<S extends IService<E>, E> { ? ? ?@Autowired ?? ?protected S baseService; ? ? ?@ApiOperation("增") ?? ?@PostMapping("/insert") ?? ?public ResponseUtils insert(@RequestBody E entity) { ?? ? ? ?baseService.save(entity); ?? ? ? ?return ResponseUtils.success("添加成功"); ?? ?} ? ? ?@ApiOperation("刪") ?? ?@PostMapping("/deleteById") ?? ?public ResponseUtils delete(@RequestBody List<Integer> ids) { ? ? ? ? ?baseService.removeByIds(ids); ?? ? ? ?return ResponseUtils.success("添加成功"); ?? ?} ? ? ?@ApiOperation("改") ?? ?@PostMapping("/updateById") ?? ?public ResponseUtils updateById(@RequestBody E entity) { ?? ? ? ?baseService.updateById(entity); ?? ? ? ?return ResponseUtils.success("添加成功"); ?? ?} ? ? ?@ApiOperation("查") ?? ?@GetMapping("/getById") ?? ?public ResponseUtils getById(@RequestParam Integer id) { ? ? ? ? ?return ResponseUtils.success(baseService.getById(id)); ?? ?} ? ? ?@ApiOperation("存") ?? ?@PostMapping("/save") ?? ?public ResponseUtils save(@RequestBody E entity) { ?? ? ? ?baseService.saveOrUpdate(entity); ?? ? ? ?return ResponseUtils.success("添加成功"); ?? ?} ? ? ?@ApiOperation("list查") ?? ?@PostMapping("/list") ?? ?public ResponseUtils list(@RequestBody E entity) { ?? ? ? ?QueryWrapper<E> queryWrapper = ApprenticeUtil.getQueryWrapper(entity); ?? ? ? ?List<E> list = baseService.list(queryWrapper); ?? ? ? ?return ResponseUtils.success(list); ?? ?} ? ? ?@ApiOperation("page查") ?? ?@PostMapping("/page") ?? ?public ResponseUtils page(@RequestBody PageParamDto<E> pageParamDto) { ?? ? ? ?//限制條件 ?? ? ? ?if (pageParamDto.getPage() < 1) { ?? ? ? ? ? ?pageParamDto.setPage(1); ?? ? ? ?} ? ? ? ? ?if (pageParamDto.getSize() > 100) { ?? ? ? ? ? ?pageParamDto.setSize(100); ?? ? ? ?} ?? ? ? ?Page<E> page = new Page<>(pageParamDto.getPage(), pageParamDto.getSize()); ?? ? ? ?QueryWrapper<E> queryWrapper = new QueryWrapper<>(); ?? ? ? ?//升序 ?? ? ? ?String asc = pageParamDto.getAsc(); ?? ? ? ?if (!StrUtil.isEmpty(asc) && !"null".equals(asc)) { ?? ? ? ? ? ?String[] split = asc.split(","); ?? ? ? ? ? ?queryWrapper.orderByAsc(split); ?? ? ? ?} ?? ? ? ?//降序 ?? ? ? ?String desc = pageParamDto.getDesc(); ?? ? ? ?if (!StrUtil.isEmpty(desc) && !"null".equals(desc)) { ?? ? ? ? ? ?String[] split = desc.split(","); ?? ? ? ? ? ?queryWrapper.orderByDesc(split); ?? ? ? ?} ?? ? ? ?Page<E> ePage = baseService.page(page, queryWrapper); ?? ? ? ?return ResponseUtils.success(ePage); ?? ?} ? ? ?@ApiOperation("獲取數(shù)量") ?? ?@PostMapping("/count") ?? ?public ResponseUtils count(@RequestBody E entity) { ?? ? ? ?QueryWrapper<E> queryWrapper = ApprenticeUtil.getQueryWrapper(entity); ?? ? ? ?long count = baseService.count(queryWrapper); ?? ? ? ?return ResponseUtils.success(count); ?? ?} ? } ?

這段Java代碼展示了一個基本的基于Spring Boot框架開發(fā)的RESTful API接口實(shí)現(xiàn)。BaseController是一個較為通用的Controller基類,通過泛型使其可以處理各種實(shí)體類型對應(yīng)的請求(比如增、刪、改、查等)。

具體來說,該類中包含了五個基本HTTP操作(POST, GET),通過不同參數(shù)和請求方式對實(shí)體對象進(jìn)行CRUD操作,即添加(insert)、刪除(delete)、修改(update)、查詢(getById)、存儲(save)、列表查詢(list)、分頁查詢(page)、統(tǒng)計數(shù)量(count)。同時,通過Spring Boot自帶的Web開發(fā)框架中的注解,將每個方法暴露為一個Restful API。

需要注意的是,該控制器只是一個模板,實(shí)際使用時需要繼承該控制器并傳入相應(yīng)的Service類作為泛型S的參數(shù),并實(shí)現(xiàn)具體的CRUD方法。

第四步,由于mybatisplus默認(rèn)是不支持分頁的,我們需要配置一下使他支持

java復(fù)制代碼import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; ?@Configuration public class MybatisPlusConfig { ? ?? ?/** 設(shè)置分頁插件 ?? ? * @Param: [] ?? ? * @return: com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor ?? ? * @Author: MaSiyi ?? ? * @Date: 2021/11/26 ?? ? */ ?? ?@Bean ?? ?public MybatisPlusInterceptor mybatisPlusInterceptor() { ?? ? ? ?MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); ?? ? ? ?interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); ?? ? ? ?return interceptor; ?? ?} ? }

第五步,我們在自己的controller類中繼承BaseController類

java復(fù)制代碼import com.wangfugui.apprentice.dao.domain.Dynamic; import com.wangfugui.apprentice.service.IDynamicService; import io.swagger.annotations.Api; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; ?/** ?* <p> ?* 動態(tài)表 前端控制器 ?* </p> ?* ?* @author MrFugui ?* @since 2021-11-23 ?*/ @RestController @RequestMapping("/apprentice/dynamic") @Api("動態(tài)管理") public class DynamicController extends BaseController<IDynamicService, Dynamic>{ ?}

這樣就可以有默認(rèn)的增刪改查了

java復(fù)制代碼 import com.wangfugui.apprentice.dao.domain.Blog; import com.wangfugui.apprentice.service.IBlogService; import io.swagger.annotations.Api; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; ?/** ?* <p> ?* 博客表 前端控制器 ?* </p> ?* ?* @author MrFugui ?* @since 2021-11-25 ?*/ @RestController @RequestMapping("/apprentice/blog") @Api(tags = "博客管理") public class BlogController extends BaseController<IBlogService, Blog>{ ? ?} ?

這樣就能使用啦!

MybatisPlus不好用,帥小伙一氣之下寫了個MybatisPlusPro的評論 (共 條)

分享到微博請遵守國家法律
温州市| 阳原县| 泽库县| 荔浦县| 柏乡县| 彭水| 改则县| 米泉市| 盐源县| 思南县| 郴州市| 汉阴县| 茂名市| 宣汉县| 应城市| 乐业县| 盐亭县| 岱山县| 邵阳县| 双柏县| 定兴县| 霍邱县| 台北市| 平南县| 平度市| 阿合奇县| 深圳市| 宜丰县| 共和县| 常山县| 安溪县| 奉节县| 玉屏| 庆元县| 辽宁省| 宜昌市| 江源县| 衡东县| 曲周县| 吉林省| 广德县|