一、多表聯合分頁查詢
1.多表聯合查詢結果集建議使用VO類,當然也可以使用resultMap
package com.cjhx.tzld.entity.vo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.cjhx.tzld.entity.TContent; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; @Data @ApiModel(value="TContentVo", description="內容池多表聯合數據對象") public class TContentVo extends TContent { @ApiModelProperty(value = "編號") private Integer cid; @ApiModelProperty(value = "內容標題") private String title; @ApiModelProperty(value = "作者Id") @TableField("authorId") private Integer authorId; @ApiModelProperty(value = "時間") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") //返回時間類型 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") //接收時間類型 private Date time; @ApiModelProperty(value = "內容") private String content; @ApiModelProperty(value = "作者姓名") private String author; @ApiModelProperty(value = "話題") private String topic; @ApiModelProperty(value = "模塊編號") private int moduleNum; @ApiModelProperty(value = "模塊") private String module; public TContentVo() { } public TContentVo(Integer cid, String title, Date time, String content, String author, String topic, int moduleNum) { this.cid = cid; this.title = title; this.time = time; this.content = content; this.author = author; this.topic = topic; this.moduleNum = moduleNum; } }
2.controller
package com.cjhx.tzld.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cjhx.tzld.common.Result; import com.cjhx.tzld.entity.TContent; import com.cjhx.tzld.entity.TContentRelationFund; import com.cjhx.tzld.entity.TTopicPk; import com.cjhx.tzld.entity.vo.TContentVo; import com.cjhx.tzld.service.TContentService; import io.swagger.annotations.*; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.Date; import java.util.List; /** * @since 2022-02-28 */ @RestController @RequestMapping("/content") @Api("內容池模塊") public class ContentController { @Resource private TContentService contentService; @ApiImplicitParams({ @ApiImplicitParam(name = "cid",value = "cid",dataType = "int",defaultValue = "0",required = false), @ApiImplicitParam(name = "title",value = "標題",dataType = "String",defaultValue = "",required = false), @ApiImplicitParam(name = "author",value = "作者姓名",dataType = "String",defaultValue = "",required = false), @ApiImplicitParam(name = "time",value = "發布時間",dataType = "Date",defaultValue = "",required = false), @ApiImplicitParam(name = "content",value = "內容",dataType = "String",defaultValue = "",required = false), @ApiImplicitParam(name = "topic",value = "話題",dataType = "String",defaultValue = "",required = false), @ApiImplicitParam(name = "moduleNum",value = "投放模塊 1熱點速遞 2基會直達",dataType = "int",defaultValue = "",required = false), @ApiImplicitParam(name = "pageIndex",value = "頁碼",dataType = "int",defaultValue = "1",required = false), @ApiImplicitParam(name = "pageSize",value = "每頁數量",dataType = "int",defaultValue = "10",required = false) }) @ApiResponses({ @ApiResponse(code = 200,message = "OK",response = TContent.class) }) @ApiOperation(value="分頁獲取內容接口(Web端)", notes="支持多條件查詢",httpMethod = "GET") @RequestMapping(value = "/getContentPage",method = RequestMethod.GET) public Result getContentPage(@RequestParam(defaultValue = "0",required = false) int cid, @RequestParam(defaultValue = "",required = false) String title, @RequestParam(defaultValue = "",required = false) String author, @RequestParam(required = false) Date time, @RequestParam(defaultValue = "",required = false) String content, @RequestParam(defaultValue = "",required = false) String topic, @RequestParam(defaultValue = "0",required = false) int moduleNum, @RequestParam(defaultValue = "1",required = false) int pageIndex, @RequestParam(defaultValue = "10",required = false) int pageSize) throws Exception{ try { IPage<TContentVo> byPage = contentService.findByPage(new Page<TContentVo>(pageIndex, pageSize),new TContentVo(cid, title, time, content, author, topic, moduleNum)); return Result.success(byPage); }catch (Exception e){ return Result.serviceFail(e.getMessage()); } } }
3.service
package com.cjhx.tzld.service.impl; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cjhx.tzld.common.PageUtil; import com.cjhx.tzld.entity.TContent; import com.cjhx.tzld.entity.vo.TContentVo; import com.cjhx.tzld.mapper.TContentMapper; import com.cjhx.tzld.service.TContentService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; /** * @since 2022-02-28 */ @Service public class TContentServiceImpl extends ServiceImpl<TContentMapper, TContent> implements TContentService { @Resource private TContentMapper tContentMapper; @Override public IPage<TContentVo> findByPage(Page<TContentVo> page, TContentVo contentVo) { return tContentMapper.findByPage(page,contentVo); } }
4.mapper
package com.cjhx.tzld.mapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cjhx.tzld.entity.TContent; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.cjhx.tzld.entity.vo.TContentVo; import org.apache.ibatis.annotations.Param; /** * @since 2022-02-28 */ public interface TContentMapper extends BaseMapper<TContent> { IPage<TContentVo> findByPage(Page<TContentVo> page, @Param("contentVo") TContentVo contentVo); }
5.mapper.xml,注意入參 contentVo
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cjhx.tzld.mapper.TContentMapper"> <select id="findByPage" resultType="com.cjhx.tzld.entity.vo.TContentVo" parameterType="com.cjhx.tzld.entity.vo.TContentVo"> SELECT t.`cid`,t.`authorId`,a.`name`,t.`title`,t.`time`,t.`content`,p.`topic`,h.`title` AS `module` FROM `t_content` t LEFT JOIN `t_author` a ON a.`aid`=t.`authorId` LEFT JOIN `t_topic_pk` p ON p.`cid` = t.`cid` LEFT JOIN `t_hot_express` h ON h.`cid` = t.`cid` UNION ALL SELECT t.`cid`,t.`authorId`,a.`name`,t.`title`,t.`time`,t.`content`,p.`topic`,f.`title` AS `module` FROM `t_content` t LEFT JOIN `t_author` a ON a.`aid`=t.`authorId` LEFT JOIN `t_topic_pk` p ON p.`cid` = t.`cid` LEFT JOIN `t_fund_point` f ON f.`cid` = t.`cid` <where> <if test="contentVo.cid > 0"> and cid = #{contentVo.cid}</if> <if test="contentVo.title != null and contentVo.title != ''"> and t.title like concat('%', #{contentVo.title}, '%')</if> <if test="contentVo.author != null and contentVo.author != ''"> and a.author like concat('%', #{contentVo.author}, '%')</if> <if test="contentVo.time != null"> and t.time =${contentVo.time}</if> <if test="contentVo.content != null and contentVo.content != ''"> and t.content like concat('%', #{contentVo.content}, '%')</if> <if test="contentVo.topic != null and contentVo.topic != ''"> and p.topic like concat('%', #{contentVo.topic}, '%')</if> <if test="contentVo.moduleNum == 1"> and f.currentState = -1</if> <if test="contentVo.moduleNum == 2"> and h.currentState = -1</if> </where> order by time desc </select> </mapper>
二、找不到mapper
首先排除 @MapperScan("com.cjhx.tzld.mapper")已添加
1.首先配置文件掃描,mapper-locations:classpath:/com/cjhx/tzld/mapper/xml/*.xml
mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath:/com/cjhx/tzld/mapper/xml/*.xml
2.在pom.xml的<build>添加xml資源
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <!--引入mapper對應的xml文件--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
三、配置匯總maven
<dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1.tmp</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.1.tmp</version> </dependency> <!-- 添加 模板引擎 依賴 --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- 引入swagger-bootstrap-ui包 /doc.html--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> </dependencies>
四、自動生成代碼
generatorConfig.xml放在當前項目下與src一個層級
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自動生成的注釋 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--數據庫連接的信息:驅動類、連接地址、用戶名、密碼 #######修改1:修改成自己的數據庫名,用戶及密碼--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/eladmin?useSSL=true" userId="root" password="123456"> </jdbcConnection> <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL 和 NUMERIC 類型解析為java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成PO類的位置 #######修改2:修改生成實體類文件的包名--> <javaModelGenerator targetPackage="me.zhengjie.pojo" targetProject=".\src\main\java"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> <!-- 從數據庫返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 #######修改3:mapper.xml文件的包名--> <sqlMapGenerator targetPackage="dbconfig" targetProject=".\src\main\resources"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 #######4:mapper.xml文件的路徑--> <javaClientGenerator type="XMLMAPPER" targetPackage="me.zhengjie.mapper" targetProject=".\src\main\java"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定數據庫表 --> <table schema="" tableName="bd_additional"></table> <table schema="" tableName="bd_claimdocuments"></table> <table schema="" tableName="bd_customer"></table> <table schema="" tableName="bd_documents"></table> <table schema="" tableName="bd_insuredinfo"></table> <table schema="" tableName="bd_policyholderinfo"></table> <table schema="" tableName="bd_settleclaim"></table> <table schema="" tableName="bd_warranty"></table> </context> </generatorConfiguration>
GeneratorCode 執行main方法生成代碼
package me.zhengjie; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.po.TableFill; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import java.util.ArrayList; public class GeneratorCode { public static void main(String[] args) { // 需要構建一個 代碼自動生成器 對象 AutoGenerator mpg = new AutoGenerator(); // 配置策略 // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath+"/src/main/java"); gc.setAuthor("lanhaifeng"); gc.setOpen(false); gc.setFileOverride(false); // 是否覆蓋 gc.setServiceName("%sService"); // 去Service的I前綴 gc.setIdType(IdType.ID_WORKER); gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(true); mpg.setGlobalConfig(gc); //2、設置數據源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/eladmin?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("zhengjie"); pc.setParent("me"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("bd_additional","bd_claimdocuments","bd_customer","bd_documents", "bd_insuredinfo","bd_policyholderinfo","bd_settleclaim","bd_warranty" ); // 設置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 自動lombok; strategy.setLogicDeleteFieldName("deleted"); strategy.setTablePrefix("bd_");//去掉表名前綴 // 自動填充配置 TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); // 樂觀鎖 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2 mpg.setStrategy(strategy); mpg.execute(); //執行 } }
五、查詢部分字段
大多時候不需要查詢整個表的所有字段,只想查詢自己想要的
QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.select("name", "phone").eq("age",25); List<User> users = userMapper.selectList(queryWrapper);
屏蔽某些字段
ueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.select(User.class, info -> !info.getColumn().equals("age") && !info.getColumn().equals("address")).eq("name","jack"); List<User> users = userMapper.selectList(queryWrapper);
六、分頁不顯示總條數
package me.zhengjie.config; import org.mybatis.spring.annotation.MapperScan; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration public class MybatisPlusConfig { /** * 分頁插件 * @return */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }