MyBatis Generator 代码去重分页查询 - 使用 PageHelper 和自定义 SQL
MyBatis Generator 代码去重分页查询 - 使用 PageHelper 和自定义 SQL
使用 MyBatis Generator 生成的代码,想要根据其中一个字段去重复分页查询内容,可以使用 MyBatis 的分页插件 PageHelper 和自定义 SQL 语句实现。
1. 配置 PageHelper 插件
首先,在 MyBatis 的配置文件中配置 PageHelper 插件:
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
2. 定义自定义 SQL 语句
然后,在 Mapper 接口中定义自定义 SQL 语句,使用 PageHelper 进行分页查询:
public interface MyMapper {
@Select("SELECT DISTINCT column_name FROM table_name ORDER BY column_name DESC")
List<String> selectDistinctColumnName();
@Select("SELECT * FROM table_name WHERE column_name = #{columnName}")
@ResultMap("BaseResultMap")
List<MyEntity> selectByColumnName(@Param("columnName") String columnName);
}
3. Service 层调用
最后,在 Service 层中调用 Mapper 接口的方法,使用 PageHelper 进行分页查询:
@Service
public class MyService {
@Autowired
private MyMapper myMapper;
public PageInfo<MyEntity> selectByColumnName(String columnName, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<MyEntity> list = myMapper.selectByColumnName(columnName);
return new PageInfo<>(list);
}
public List<String> selectDistinctColumnName() {
return myMapper.selectDistinctColumnName();
}
}
通过以上步骤,就可以实现根据某个字段去重复分页查询了。
注意:
column_name和table_name请替换成实际的字段名和表名。BaseResultMap是 MyBatis Generator 生成的结果映射。MyEntity是 MyBatis Generator 生成的实体类。PageInfo类来自 PageHelper 插件,用于获取分页结果信息。
希望本文能够帮助您更好地理解 MyBatis Generator 代码去重分页查询的实现方式。
原文地址: https://www.cveoy.top/t/topic/kfDt 著作权归作者所有。请勿转载和采集!