mybatisplus在groupBy使用mysql的date_format
可以使用MybatisPlus的Wrapper来实现MySQL的date_format函数,在groupBy中使用,具体实现如下:
- 添加依赖
在pom.xml中添加MybatisPlus和MySQL驱动的依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
- 使用Wrapper
使用Wrapper来构建查询条件,然后在groupBy中使用MySQL的date_format函数:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> listUsersByDate(String date) {
LocalDateTime dateTime = LocalDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME);
// 构建查询条件
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("date_format(create_time, '%Y-%m-%d') as create_date", "count(*) as total")
.eq("status", 1)
.ge("create_time", dateTime.withHour(0).withMinute(0).withSecond(0))
.le("create_time", dateTime.withHour(23).withMinute(59).withSecond(59))
.groupBy("create_date")
.orderByAsc("create_date");
// 查询结果
return userMapper.selectList(wrapper);
}
}
在上面的代码中,我们使用QueryWrapper构建了查询条件,使用select方法指定查询的字段,其中date_format函数用来格式化create_time字段,以便在groupBy中使用;groupBy方法指定按照create_date字段分组;orderByAsc方法指定按照create_date字段升序排序。
最后调用selectList方法执行查询,返回符合条件的User列表。
需要注意的是,在MySQL中date_format函数返回的是字符串类型,而在Java中我们使用LocalDateTime类型表示日期时间,因此在构建查询条件时需要使用LocalDateTime的with方法来指定时间范围
原文地址: https://www.cveoy.top/t/topic/hq3o 著作权归作者所有。请勿转载和采集!