springboot整合mybatisplus
问题描述:
mybatisplus在mybatis的基础上,增加了许多功能,比如:更多的通用mapper和分页;那么我们该怎么来使用这些功能呢?下面详细介绍。
解决方法:
一、配置
1、加入依赖
<!-- MyBatisPlus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.5.7</version> </dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
2、编写代码生成器,运行后会生成代码文件
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList; import java.util.List; public class Generator { public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String oPath = System.getProperty("user.dir");//得到当前项目的路径 gc.setOutputDir(oPath + "/src/main/java"); //生成文件输出根目录 gc.setAuthor("XueHeng"); // 作者 gc.setOpen(false); // 生成代码后是否打开文件 gc.setFileOverride(true);// 是否覆盖文件 //gc.setActiveRecord(true);// 开启 activeRecord 模式 gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);;// XML ResultMap gc.setBaseColumnList(true);;// XML columList gc.setSwagger2(true); //实体属性 Swagger2 注解 gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/company_frame?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("13037489030"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.system"); // 指定包 mpg.setPackageInfo(pc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); strategy.setEntityTableFieldAnnotationEnable(true); //生成@TableField strategy.setInclude(new String[] { "sys_dept","sys_file","sys_log","sys_permission", "sys_role","sys_role_permission","sys_user_role", "sys_user","sys_rotation_chart" }); // 需要生成的表 strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix("sys_"); //去掉表前缀 mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
3、在启动类Application中添加扫描mapper接口的注解
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.system.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
4、在application.properties中配置mapperXml文件的路径
# springboot启动的时候会扫描这个mapper文件夹下的所有.xml文件 # 并和mapper接口的类和方法进行匹配 mybatis.mapper-locations=classpath:mapper/*.xml
5、编写MybatisPlusConfigure类,配置分页插件
import com.baomidou.mybatisplus.core.parser.ISqlParser; import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; @Configuration public class MybatisPlusConfigure { /** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); List<ISqlParser> sqlParserList = new ArrayList<>(); // 攻击 SQL 阻断解析器、加入解析链 sqlParserList.add(new BlockAttackSqlParser()); paginationInterceptor.setSqlParserList(sqlParserList); return paginationInterceptor; } }
二、使用
下面主要介绍分页的使用
1、数据库生成实体 User
@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("sys_user") @ApiModel(value="User对象", description="") public class User implements Serializable { private static final long serialVersionUID = 1L; public static final String roleId = "6293142a-2e7c-4df5-87d1-4781e476d20d"; @ApiModelProperty(value = "用户id") @TableId("id") private String id; @ApiModelProperty(value = "账户名称") @TableField("username") private String username; @ApiModelProperty(value = "加密盐值") @TableField("salt") private String salt; @ApiModelProperty(value = "用户密码密文") @TableField("password") private String password; @ApiModelProperty(value = "手机号码") @TableField("phone") private String phone; @ApiModelProperty(value = "部门id") @TableField("dept_id") private String deptId; @ApiModelProperty(value = "真实名称") @TableField("real_name") private String realName; @ApiModelProperty(value = "昵称") @TableField("nick_name") private String nickName; @ApiModelProperty(value = "邮箱(唯一)") @TableField("email") private String email; @ApiModelProperty(value = "账户状态(1.正常 2.锁定 )") @TableField("status") private Integer status; @ApiModelProperty(value = "性别(1.男 2.女)") @TableField("sex") private Integer sex; @ApiModelProperty(value = "是否删除(1未删除;0已删除)") @TableField("deleted") private Integer deleted; @ApiModelProperty(value = "创建人") @TableField("create_id") private String createId; @ApiModelProperty(value = "更新人") @TableField("update_id") private String updateId; @ApiModelProperty(value = "创建来源(1.web 2.android 3.ios )") @TableField("create_where") private Integer createWhere; @ApiModelProperty(value = "创建时间") @TableField("create_time") private Date createTime; @TableField("update_time") private Date updateTime; /** * 部门名称 */ @TableField(exist = false) private String deptName; }
2、请求VO UserPageReqVO
@Data public class UserPageReqVO { @ApiModelProperty(value = "当前第几页") private Integer pageNum=1; @ApiModelProperty(value = "当前页数量") private Integer pageSize=10; @ApiModelProperty(value = "用户id") private String userId; @ApiModelProperty(value = "账号") private String username; @ApiModelProperty(value = "昵称") private String nickName; @ApiModelProperty(value = "账户状态(1.正常 2.锁定 ") private Integer status; @ApiModelProperty(value = "开始时间") private String startTime; @ApiModelProperty(value = "结束时间") private String endTime; }
3、响应VO PageVO
@Data public class PageVO <T>{ /** * 总记录数 */ @ApiModelProperty(value = "总记录数") private Long totalRows; /** * 总页数 */ @ApiModelProperty(value = "总页数") private Long totalPages; /** * 当前第几页 */ @ApiModelProperty(value = "当前第几页") private Long pageNum; /** * 每页记录数 */ @ApiModelProperty(value = "每页记录数") private Integer pageSize; /** * 当前页记录数 */ @ApiModelProperty(value = "当前页记录数") private Integer curPageSize; /** * 数据列表 */ @ApiModelProperty(value = "数据列表") private List<T> list; }
4、控制层
@RestController @RequestMapping("api") @Api(tags = "用户") public class UserController{ @Autowired private UserService userService; @PostMapping("/users") @ApiOperation("用户列表") @RequiresPermissions("sys:user:list") public DataResult<PageVO<User>> getAllDept(@RequestBody UserPageReqVO vo){ DataResult result =DataResult.success(); result.setData(this.userService.pageInfo(vo)); return result; } }
5、service层
public interface UserService extends IService<User> { /* 获取所有用户信息(分页) */ public PageVO<User> pageInfo(UserPageReqVO vo); }
6、service实现类:这里要注意的是,page必须要传到mapper层去
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public PageVO<User> pageInfo(UserPageReqVO vo) { Page<User> page = new Page<>(vo.getPageNum(),vo.getPageSize()); IPage<User> users = this.baseMapper.selectAll(page,vo);
return PageUtil.getPage(users); } }
7、mapper层
public interface UserMapper extends BaseMapper<User> { /* 获取所有用户 */ public IPage<User> selectAll(Page page,@Param("vo") UserPageReqVO vo); }
8、xml
<select id="selectAll" resultType="com.system.entity.User" parameterType="com.system.vo.request.UserPageReqVO"> select u.*,d.name deptName from sys_user u LEFT JOIN sys_dept d ON (u.dept_id = d.id) <where> u.deleted=1 <if test="vo.userId !=null and vo.userId != ''"> and u.id=#{vo.userId} </if> <if test="vo.username !=null and vo.username != ''"> and u.username like concat('%',#{vo.username},'%') </if> <if test="vo.nickName !=null and vo.nickName != ''"> and u.nick_name like concat('%',#{vo.nickName},'%') </if> <if test="vo.status !=null and vo.status != '' or vo.status==0"> and u.status =#{vo.status} </if> <if test="vo.startTime !=null and vo.startTime != ''"> and u.create_time >= #{vo.startTime} </if> <if test="vo.endTime !=null and vo.endTime != ''"> and u.create_time <= #{vo.endTime} </if> </where> </select>
9、编写自定义分页工具类
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.system.vo.response.PageVO; /** * 分页工具类 */ public class PageUtil { private PageUtil(){} public static <T> PageVO<T> getPage(IPage<T> list){ PageVO<T> result=new PageVO<>(); if(list instanceof Page){ Page<T> page= (Page<T>) list; result.setTotalRows(page.getTotal()); result.setList(page.getRecords()); } return result; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步