Mybatis在循环中获取序列值再启动事务后重复
for (SysAttachment attachment : pactList){// 判断该附件是否已经传输过EntityWrapper<FixEquiPactLog> wrapper = new EntityWrapper<>();wrapper.eq("ATTACHMENT_ID",attachment.getId());List<FixEquiPactLog> selectList = fixEquiPactLogMapper.selectList(wrapper);if (selectList.size() != 0){continue;}FixEquiPactLog log = new FixEquiPactLog();log.setXh(fixEquiPactLogMapper.getNextVal());log.setBoeNo(boeNo);log.setAttachmentId(attachment.getId());EquiPayMain main = equiPayMainMapper.selectById(attachment.getBillId());log.setPaymentNo(main.getPayBillNo());log.setVendorCode(sysVendorMapper.selectById(main.getVenId()).getVenCode());log.setAttachmentType("purcPay".equals(attachment.getBillType()) ? 2 : 1);log.setContractCode(main.getContractNo());log.setFileName(attachment.getFilename());log.setFilePath(attachment.getFilePath());list.add(log);}
上述代码未开启事务注解@Transactional(_rollbackFor = Exception.class)_时正常获取序列值,开启后,获取序列值SQL只查询一次,并循环为每个实体赋值
解决方法
在mybatis的XML文件中关闭缓存
<select id="getNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">select S_FIX_EQUI_PACT_LOG.NEXTVAL from dual</select>
