酷代码 AI
菜单
服务商

不写sql 纯mybatis-plus 实现取某个字段最大值 只返回该值

使用 MyBatis-Plus 实现取某个字段的最大值并只返回该值,可以通过 `LambdaQueryWrapper` 和 `select` 方法来实现。以下是一个示例代码: 假设你有一个实体类 `User`,其中有一个字段 `age`,你想要获取 `age` 字段的最大值。 1. 实体类: ```java import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; @TableName("user") public class User { private Long id; @TableField("age") private Integer age; // getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } ``` 2. Mapper 接口: ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> { } ``` 3. Service 层: ```java import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserMapper userMapper; public Integer getMaxAge() { LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.select(User::getAge).orderByDesc(User::getAge).last("limit 1"); User user = userMapper.selectOne(queryWrapper); return user != null ? user.getAge() : null; } } ``` 4. Controller 层(可选): ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/max-age") public Integer getMaxAge() { return userService.getMaxAge(); } } ``` 在这个示例中,我们使用了 `LambdaQueryWrapper` 来构建查询条件,并通过 `select` 方法指定只选择 `age` 字段。然后使用 `orderByDesc` 方法按 `age` 字段降序排序,并通过 `last("limit 1")` 方法限制结果集为一条记录。调用 `selectOne` 方法获取结果,并返回 `age` 字段的值。 这样就可以实现只返回某个字段的最大值。 [2024-10-17 15:01:29 | AI写代码神器 | 566点数解答]

相关提问
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]