技术干货程序员

Spring Data JPA坑点记录

2017-12-13  本文已影响0人  Joryun

一、分页查询

场景:动态查询,分页查询,根据传入不同的状态,分别查询不同数据表,并且在传入page对象之前用map进行VO转换。而pageable的使用地方不同影响到了分页数据的正确性,以此进行探讨。

前提:Page对象封于VO内,返回数据包括了分页数据

@ApiModelProperty("记录")
private Page<ActivityRecordVO> activityRecordVOList;

@ApiModelProperty("数量")
private Integer num = 0;

@ApiModelProperty("金额")
private BigDecimal totalMoney = BigDecimal.valueOf(0);

错误运用:

List<ActivityRecordVO> activityRecordVOList = new ArrayList<>();

        if (receiveSendRecordRequestVO.getSendOrReceiveType() == SendOrReceiveType.RECEIVE) {

            List<ChallengeRecord> challengeRecordList = challengeRecordDao.findByUserIdAndDeleteType(userId,
                    DeleteType.FALSE);
            if (!CollectionUtils.isEmpty(challengeRecordList)) {
                activityRecordVOList = challengeRecordList.stream()
                        .map(this::challengeRecordToActivityRecordVO)
                        .collect(Collectors.toList());
            }

        } else if (receiveSendRecordRequestVO.getSendOrReceiveType() == SendOrReceiveType.SEND) {

            List<Activity> activityList = activityDao.findByUserIdAndDeleteType(userId, DeleteType.FALSE);
            if (!CollectionUtils.isEmpty(activityList)) {
                activityRecordVOList = activityList.stream()
                        .map(this::activityTOActivityRecordVO)
                        .collect(Collectors.toList());
            }
        }
activityReceiveSendRecordVO.setActivityRecordVOList(new PageImpl<>(activityRecordVOList,
                    pageable, activityRecordVOList.size()));

解析:传入的pageable只在set进VO的时候,用new PageIml将List转为page对象,前端报的问题 虽然总页数、总条数均为正确,但第一页的条数是全部 ,数据异常!

正确参考做法:

采用Specifications先根据查询条件动态查询并map出相应分页对象(此块代码因需求而异),这时 findAll 传入的pageable是生效的,便会显现正确的分页信息。

代码块参考:

xxxCommonSpecUtil 是自封的specification工具类,与原生spring data jpa原生查询方法类似。

Page<ActivityRecordVO> page = new PageImpl<>(activityRecordVOList, pageable, activityRecordVOList.size());

        if (receiveSendRecordRequestVO.getSendOrReceiveType() == SendOrReceiveType.RECEIVE) {

            Specifications<ChallengeRecord> spec = Specifications.where(
                    challengeCommonSpecUtil.equal("userId", userId))
                    .and(challengeCommonSpecUtil.equal("deleteType", DeleteType.FALSE));
            page = challengeRecordDao.findAll(spec, pageable).map(this::challengeRecordToActivityRecordVO);

        } else if (receiveSendRecordRequestVO.getSendOrReceiveType() == SendOrReceiveType.SEND) {

            Specifications<Activity> spec = Specifications.where(
                    activityCommonSpecUtil.equal("userId", userId))
                    .and(activityCommonSpecUtil.equal("deleteType", DeleteType.FALSE));
            page = activityDao.findAll(spec, pageable).map(this::activityTOActivityRecordVO);
        }

注:activityReceiveSendRecordVO为封装的VO,包含了返回的Page对象

activityReceiveSendRecordVO.setActivityRecordVOList(page);

二、事务,更新实体,并查询

场景:@Transactional事务,更新用户余额(处理并发问题),更新完毕返回VO带上用户剩余余额,但却非更新后的余额。

更新逻辑代码:

userWebService.updateBalanceAfterTransaction(userId, transactionRecordAddVO.getMoney(),user.getBalance());
@Transactional
    public void updateBalanceAfterTransaction(Integer userId, BigDecimal money, BigDecimal userBalance) {
        int i = userDao.updateBalanceAfterTransaction(userId, money, userBalance);
        if (i == 0) {
            throw new ValidationException(MessageCodes.TRANSACTION_RECEIVE_IS_ERROR);
        }
    }
@Modifying
    @Query(value = "update User u set u.balance = u.balance - ?2 where u.id = ?1 and u.balance = ?3")
    int updateBalanceAfterTransaction(Integer userId, BigDecimal money, BigDecimal userBalance);

解析:
在jpa中使用 @Modifying ,虽然事务已经能够更新,但是在循环更新的时候,执行modify语句后的查询的实体仍然是没有更新的。

执行完modifying query, EntityManager可能会包含过时的数据,因为EntityManager不会自动清除实体。
只有添加clearAutomatically属性,EntityManager才会自动清除实体对象。

添加代码:

@Modifying(clearAutomatically = true)

改正后的示例代码:

@Modifying(clearAutomatically = true)
    @Query(value = "update User u set u.balance = u.balance - ?2 where u.id = ?1 and u.balance = ?3")
    int updateBalanceAfterTransaction(Integer userId, BigDecimal money, BigDecimal userBalance);

总结

使用了这么长时间spring data jpa,觉得Specifications巨好用,也不容易出错,也是我喜欢的编码风格,而new PageImpl<>()这种简单粗暴的方法我一般都用在查询数据关联太多表的情况,在最后直接返回,更深层次的还需要再探讨!

上一篇下一篇

猜你喜欢

热点阅读