MyBatis-Plus是一款国产的框架,优化了许多操作。
本次主要记录一下,多表联查和分页的使用。
添加依赖
<!-- Mybatis 的增强工具包,用于简化开发。 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- Mybatis 的增强工具包,用于简化开发。 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3</version>
</dependency>
配置分页插件
@Configuration
public class MybatisConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
定义VO类
由于我的Bot
类需要多两个属性,分别是
private String username;
private String photo;
而这两个属性来自用户User
表,因此创建了一个UserBotVo
类,把上面两个属性都放在里面,具体代码如下:
@Data
public class UserBotVo implements Serializable {
private Integer id;
private Integer userId;
/* 此处省略... */
private String username;
private String photo;
}
创建Mapper
参数为分页对象(+数据)。
@Mapper
public interface UserBotMapper extends BaseMapper<UserBotVo> {
@Select("SELECT * from bot a inner JOIN user b on a.user_id = b.id and a.game_id = #{gameId} order by a.rating desc")
List<UserBotVo> selectUserBotListPage(Page<UserBotVo> iPage, Integer gameId);
}
Service类
public interface GetRankingService {
JSONObject getList(Integer page, Integer gameId);
}
ServiceImpl类
@Service
public class GetRankingServiceImpl implements GetRankingService {
@Autowired
private UserBotMapper userBotMapper;
@Override
public JSONObject getList(Integer page, Integer gameId) {
Page<UserBotVo> userBotIPage = new Page<>(page, 5);
List<UserBotVo> userBotVoList = userBotMapper.selectUserBotListPage(userBotIPage, gameId);
JSONObject resp = new JSONObject();
resp.put("userBotVoList", userBotVoList);
return resp;
}
}
page参数说明
// private List<T> records; 对象列表
// private long total; 总记录
// private long size; 每页记录数
// private long current; 当前的页数
// private List<OrderItem> orders; //和数据库列有关
// private boolean optimizeCountSql; //是否记录优化
// private boolean isSearchCount; //是否搜索