LambdaQueryWrapper怎样返回前几条
时间: 2024-04-20 14:20:37 浏览: 325
LambdaQueryWrapper是MyBatis-Plus框架中的一个查询构造器,用于构建复杂的查询条件。它提供了一种简洁的方式来编写查询语句。然而,LambdaQueryWrapper本身并不支持直接返回前几条记录的功能。要实现这个功能,可以借助MyBatis-Plus提供的分页功能来实现。
下面是一个示例代码,演示了如何使用LambdaQueryWrapper和分页功能来返回前几条记录[^1]:
```java
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getTopNUsers(int n) {
// 创建分页对象,设置每页显示的记录数为n
Page<User> page = new Page<>(1, n);
// 创建LambdaQueryWrapper对象,设置查询条件
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.orderByDesc(User::getId); // 按照id降序排序
// 调用selectPage方法进行分页查询
IPage<User> resultPage = userMapper.selectPage(page, queryWrapper);
// 返回查询结果的记录列表
return resultPage.getRecords();
}
}
```
在上述示例中,我们首先创建了一个分页对象`Page<User>`,并设置每页显示的记录数为n。然后,我们创建了一个LambdaQueryWrapper对象`queryWrapper`,并设置了查询条件和排序方式。最后,我们调用`selectPage`方法进行分页查询,并通过`resultPage.getRecords()`方法获取查询结果的记录列表。
请注意,上述示例中的`UserMapper`是一个自动生成的Mapper接口,用于执行数据库操作。你需要根据自己的实际情况进行相应的调整。
阅读全文
相关推荐













@Override
@Transactional
public void createTemporarySpotCheckOrder(CreateTemporarySpotCheckLo createTemporarySpotCheckLo) {
MaintTypeEnum maintType = MaintTypeEnum.DRC;
MaintForm maintForm;
List<MaintFormEqp> formEqps = new ArrayList<>();
List<MaintFormAction> equipmentActions = new ArrayList<>();
List<MaintFormActionInput> cells = new ArrayList<>();
String eqpCode = createTemporarySpotCheckLo.getEqpCode();
String planEffectTime = createTemporarySpotCheckLo.getPlanEffectTime();
LocalDate planDate = null;
LocalDateTime planEffectDate = null;
if (StringUtils.isNotEmpty(planEffectTime)) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
planDate = LocalDate.parse(planEffectTime, formatter);
planEffectDate = LocalDateTime.parse(planEffectTime, formatter);
}
String isImedEffect = createTemporarySpotCheckLo.getIsImedEffect();
maintForm = newForm(null, planDate, eqpCode, new MaintPlan(), MaintTypeEnum.TRC, new MaintPlanItem(), null, isImedEffect, planEffectDate);
LambdaQueryWrapper<EquipmentCapability> qm = new LambdaQueryWrapper<>();
qm.eq(EquipmentCapability::getEqpCode, eqpCode);
qm.eq(EquipmentCapability::getActive, "Y");
EquipmentCapability equipmentCapability = equipmentCapabilityMapper.selectOne(qm);
LambdaQueryWrapper<EquipmentDef> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(EquipmentDef::getEqpCode, eqpCode);
EquipmentDef equipmentDef = equipmentDefMapper.selectOne(queryWrapper);
MaintManual manual = getManual(equipmentDef.getBrandCode(), maintType, equipmentCapability, createTemporarySpotCheckLo.getDescEncode());
if (manual == null) {
throw new BusinessException("9999", "该设备不存在已激活的维保手册!");
}
//临时点检名称使用手册全名
maintForm.setMaintPlanFullname(manual.getMaintManualFullname());
//临时点检标题使用手册描述
maintForm.setFormTitle(manual.getDescription());
//表单编号和版本
maintForm.setCode(manual.getCode());
maintForm.setVersion(manual.getVersion());
//临时点检备注提示取手册中的
maintForm.setFillinComment(manual.getNotes());
//设置表单类型
maintForm.setFormType(createTemporarySpotCheckLo.getDescEncode());
MaintFormEqp formEqp = new MaintFormEqp();
formEqp.setFormCode(maintForm.getFormCode());
formEqp.setEqpCode(equipmentDef.getEqpCode());
formEqp.setMaintManualFullname(manual.getMaintManualFullname());
formEqp.setMaintType(maintType.name());
formEqp.setSortingOrder(String.valueOf(0));
formEqp.setPeriodConditionCode("UNSCHEDULED");
formEqps.add(formEqp);
String maintManualFullname = manual.getMaintManualFullname();
if (StringUtils.isNotBlank(manual.getRefMaintManualName())) {
MaintManual refMaintManual = getMaintManualByVersionOrActive(manual.getRefMaintManualName(), manual.getRefMaintManualVersion());
if (null == refMaintManual) {
throw new BusinessException("9999", "refMaintManual不存在!");
}
maintManualFullname = refMaintManual.getMaintManualFullname();
}
// equipment action record
List<MaintManualItem> manualItems = getMaintManualItems(maintManualFullname, "UNSCHEDULED");
if (CollectionUtils.isEmpty(manualItems)) {
throw new BusinessException("9999", "该设备的激活维保手册没有维护不定期点检项目!");
}
List<BasicActionWrapper> basicActions = new ArrayList<>();
for (MaintManualItem manualItem : manualItems) {
if (manualItem.getGroupAction()) {
List<BasicActionWrapper> actions = getBasicActionsOfGroup(manualItem.getActionName(), manualItem.getActionVersion());
basicActions.addAll(actions);
} else {
BasicAction action = getBasicActionByNameVersion(manualItem.getActionName(), manualItem.getActionVersion());
BasicAction basicAction = new BasicAction();
try {
BeanUtils.copyProperties(action, basicAction);
} catch (Exception e) {
throw new BusinessException("9999", "事项" + manualItem.getActionName() + "不存在" + (manualItem.getActionVersion().equals(ModelVersion.AA) ? "激活的版本!" : manualItem.getActionVersion() + "版本!"));
}
// 取manual中的PhotoRequired
basicAction.setPhotoRequired(manualItem.getPhotoRequired());
BasicActionWrapper wrapper = new BasicActionWrapper(basicAction, null);
basicActions.add(wrapper);
}
}
calculateSortOrderForActions(basicActions); // 计算每个form action的序号
for (int j = 0; j < basicActions.size(); j++) {
BasicActionWrapper actionWrapper = basicActions.get(j);
MaintFormAction formAction = new MaintFormAction();
formAction.setFormCode(maintForm.getFormCode());
formAction.setEqpCode(formEqp.getEqpCode());
formAction.setBasicActionFullname(actionWrapper.basicAction.getBasicActionFullname());
formAction.setPhotoRequired(actionWrapper.basicAction.getPhotoRequired());
formAction.setGroupActionFullname(actionWrapper.groupActionFullname);
formAction.setSortingOrder(actionWrapper.sortingOrder);
equipmentActions.add(formAction);
// action items(cells)
for (int row = 0; row < actionWrapper.basicAction.getTotalRow(); row++) {
for (int col = 0; col < actionWrapper.basicAction.getTotalCol(); col++) {
MaintFormActionInput cell = new MaintFormActionInput();
cell.setFormCode(maintForm.getFormCode());
cell.setEqpCode(equipmentDef.getEqpCode());
cell.setBasicActionFullname(actionWrapper.basicAction.getBasicActionFullname());
cell.setRow(row);
cell.setCol(col);
cell.setSortingOrder(formAction.getSortingOrder());
cells.add(cell);
}
}
}
// save records to db
maintFormMapper.insert(maintForm);
LOGGER.info("formEqps:" + formEqps);
for (MaintFormEqp maintFormEqp : formEqps) {
maintFormEqpMapper.insert(maintFormEqp);
}
LOGGER.info("equipmentActions:" + equipmentActions);
for (MaintFormAction maintFormAction : equipmentActions) {
maintFormActionMapper.insert(maintFormAction);
}
LOGGER.info("cells:" + cells);
for (MaintFormActionInput maintFormActionInput : cells) {
maintFormActionInputMapper.insert(maintFormActionInput);
}
//推送消息
LambdaQueryWrapper<SpotCheckPushSetting> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SpotCheckPushSetting::getEqpCode, eqpCode)
.eq(SpotCheckPushSetting::getNoticeType, SpotCheckPushSettingEnum.CREATED.getCode())
.eq(SpotCheckPushSetting::getDeleteStatus, "Y");
SpotCheckPushSetting setting = spotCheckPushSettingMapper.selectOne(wrapper);
String userNumber = null;
//判断是否有维护点检通知
if (setting != null) {
//获取周期频率的中文描述使用
//查询定期的维保周期
List periods = new LambdaQueryChainWrapper<>(periodMapper).list();
//基于维保周期Code将集合转化为map
Map<String, Period> periodMap = periods.stream()
.collect(Collectors.toMap(Period::getPeriodCode, Function.identity()));
Period period = periodMap.get(maintForm.getPeriodCode());
//维保周期没有维护,但是计划里面有相应的定期动作,则提示异常并结束
if (null == period) {
LOGGER.error(String.format("The period [%s] is not existed", maintForm.getPeriodCode()));
return;
}
userNumber = setting.getNoticePersonNumber();
String descEncode = createTemporarySpotCheckLo.getDescEncode();
if (descEncode.length() >= "SBGCDJ".length() &&
descEncode.substring(0, "SBGCDJ".length()).equals("SBGCDJ")) {
// 进入这个代码块如果前几位(至少和"SBGCDJ"一样长)是"SBGCDJ"
String emailContent = "有一份设备过程点检工单创建成功!"
+ "
表单:"+ maintForm.getFormTitle()
+ "
点检工单编号:" + maintForm.getFormCode()
+ "
设备:" + maintForm.getMaintObject() +"("+ equipmentDef.getDescription()+ ")"
+ "
生成时间:" + maintForm.getCreatedTimestamp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+ "
如有疑请查看:PMS设备管理系统" + jumpIp + "/platform/#/TM20/login";
String wechatContent = "有一份设备过程点检工单创建成功!"
+ "\n表单:"+ maintForm.getFormTitle()
+ "\n点检工单编号:" + maintForm.getFormCode()
+ "\n设备:" + maintForm.getMaintObject() + "(" + equipmentDef.getDescription()+ ")"
+ "\n周期频率:" + maintForm.getPeriodCode() + "(" + period.getDescription() + ")"
+ "\n生成时间:" + maintForm.getCreatedTimestamp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+ "\n如有疑请查看:PMS设备管理系统";
LogInfo logInfo = new LogInfo();
logInfo.setFormCode(maintForm.getFormCode());
logInfo.setEqpCode(maintForm.getMaintObject());
logInfo.setNoticeType(SpotCheckPushSettingEnum.CREATED.getCode());
logInfo.setUpgradeTime(setting.getUpgradeTime());
emailWeComSendBo.sendMessage(userNumber, "设备过程点检工单创建通知", emailContent, wechatContent, true, true, logInfo);
}else {
String emailContent = "有一份工艺过程点检工单创建成功!"
+ "
表单:"+ maintForm.getFormTitle()
+ "
点检工单编号:" + maintForm.getFormCode()
+ "
设备:" + maintForm.getMaintObject() +"("+ equipmentDef.getDescription()+ ")"
+ "
生成时间:" + maintForm.getCreatedTimestamp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+ "
如有疑请查看:PMS设备管理系统" + jumpIp + "/platform/#/TM20/login";
String wechatContent = "有一份工艺过程点检工单创建成功!"
+ "\n表单:"+ maintForm.getFormTitle()
+ "\n点检工单编号:" + maintForm.getFormCode()
+ "\n设备:" + maintForm.getMaintObject() + "(" + equipmentDef.getDescription()+ ")"
+ "\n周期频率:" + maintForm.getPeriodCode() + "(" + period.getDescription() + ")"
+ "\n生成时间:" + maintForm.getCreatedTimestamp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+ "\n如有疑请查看:PMS设备管理系统";
LogInfo logInfo = new LogInfo();
logInfo.setFormCode(maintForm.getFormCode());
logInfo.setEqpCode(maintForm.getMaintObject());
logInfo.setNoticeType(SpotCheckPushSettingEnum.CREATED.getCode());
logInfo.setUpgradeTime(setting.getUpgradeTime());
emailWeComSendBo.sendMessage(userNumber, "工艺过程点检工单创建通知", emailContent, wechatContent, true, true, logInfo);
}
}
}在这个方法中maintFormMapper.insert(maintForm);可以插入成功,请给出我在 /**
* 批量保存数据到数据库
*/
@Override
@Transactional
public void batchSaveData(List<MaintForm> forms, List<MaintFormEqp> formEqps,
List<MaintFormAction> equipmentActions, List<MaintFormActionInput> cells) {
if (!forms.isEmpty()) {
if (forms.stream().anyMatch(Objects::isNull)) {
throw new IllegalArgumentException("列表中存在null元素");
}
forms.forEach(form -> LOGGER.info("Form to insert: {}", form));
for (MaintForm maintForm : forms) {
maintFormMapper.insert(maintForm);
}
// maintFormMapper.maintFormBatchInsert(forms);
LOGGER.info("Saved {} forms", forms.size());
}
if (!formEqps.isEmpty()) {
maintFormEqpMapper.formEqpsBatchInsert(formEqps);
LOGGER.info("Saved {} formEqps", formEqps.size());
}
if (!equipmentActions.isEmpty()) {
maintFormActionMapper.equipmentActionsBatchInsert(equipmentActions);
LOGGER.info("Saved {} equipmentActions", equipmentActions.size());
}
if (!cells.isEmpty()) {
maintFormActionInputMapper.cellsBatchInsert(cells);
LOGGER.info("Saved {} cells", cells.size());
}
}错误的原因






