jpa+多表关联+动态拼接参数+分页查询
前言
方式一 JPQL
service
package com.cebbank.api.service.impl; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cebbank.api.constant.AuthOrUnauthEnum; import com.cebbank.api.mapper.RoleAuthMapper; import com.cebbank.api.mapper.UserRoleMapper; import com.cebbank.api.model.po.UserRolePo; import com.cebbank.api.model.qo.RoleAuthQo; import com.cebbank.api.model.suo.AuthOrUnauthSuo; import com.cebbank.api.model.vo.PageVo; import com.cebbank.api.model.vo.RoleAuthVo; import com.cebbank.api.service.RoleAuthService; import com.cebbank.api.utils.GetDifferenceListUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.stream.Collectors; @Slf4j @Service public class RoleAuthServiceImpl implements RoleAuthService { @Autowired private RoleAuthMapper roleAuthMapper; @Autowired private UserRoleMapper userRoleMapper; /** * 默认查询-根据role_id查询 * * @param qo * @return */ @Override public PageVo<RoleAuthVo> authPageList(RoleAuthQo qo) { Page<RoleAuthVo> page = new Page<>(qo.getPageNo(), qo.getPageSize()); IPage<RoleAuthVo> result = roleAuthMapper.selectRoleAuthPageList(page, qo.getRoleId()); List<RoleAuthVo> roleAuthVos = result.getRecords(); long total = result.getTotal(); PageVo<RoleAuthVo> pageVo = new PageVo<>(); pageVo.setTotal(total); pageVo.setList(roleAuthVos); return pageVo; } /** * 根据keyword搜索 * * @param qo * @return */ @Override public PageVo<RoleAuthVo> authList(RoleAuthQo qo) { Page<RoleAuthVo> page = new Page<>(qo.getPageNo(), qo.getPageSize()); String keyword = qo.getKeyword(); IPage<RoleAuthVo> result = roleAuthMapper.selectRoleAuthList(page, qo.getRoleId(), keyword); List<RoleAuthVo> roleAuthVos = result.getRecords(); long total = result.getTotal(); PageVo<RoleAuthVo> pageVo = new PageVo<>(); pageVo.setTotal(total); pageVo.setList(roleAuthVos); return pageVo; } /** * 授权或取消授权 * * @param suo */ @Override @Transactional public void authOrUnauth(AuthOrUnauthSuo suo) { String isAuth = suo.getIsAuth(); if (AuthOrUnauthEnum.AUTH.getIsAuth().equals(isAuth)) { // 授权 needAdd Integer roleId = suo.getRoleId(); List<UserRolePo> userRolePos = userRoleMapper.selectPoByRoleId(roleId); List<Integer> databaseUserIds = userRolePos.stream().map(UserRolePo::getUserId).collect(Collectors.toList()); List<Integer> sourceIds = suo.getUserIds(); List<Integer> needAddIds = GetDifferenceListUtil.getDifferenceList(sourceIds, databaseUserIds); if (CollectionUtils.isNotEmpty(needAddIds)) { needAddIds.forEach(userId -> { UserRolePo po = new UserRolePo(); po.setRoleId(roleId); po.setUserId(userId); userRoleMapper.insert(po); }); } log.info("授权成功"); } else { // 取消授权 Integer roleId = suo.getRoleId(); List<Integer> userIds = suo.getUserIds(); userRoleMapper.deleteByRoleIdAndUserIds(roleId, userIds); log.info("取消授权成功:[" + userIds + "]"); } } }
mapper
package com.cebbank.api.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cebbank.api.model.vo.RoleAuthVo; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface RoleAuthMapper extends BaseMapper<RoleAuthVo> { @Select({ "SELECT ur.id id,ur.role_id roleId,u.id userId,u.code userCode,u.name userName " + "from user_role ur, user u " + "where ur.user_id=u.id and ur.role_id=#{roleId}" }) IPage<RoleAuthVo> selectRoleAuthPageList(Page<RoleAuthVo> page, @Param("roleId") Integer roleId); @Select({ "<script>" + " SELECT " + " ur.id id, " + " ur.role_id roleId, " + " u.id userId, " + " u.code userCode, " + " u.name userName, " + " u.dpt_id deptId, " + " d.name deptName, " + " CASE " + " WHEN ur.role_id IS NULL THEN " + "'N' " + " ELSE " + "'Y' " + " END isAuth " + " FROM " + " user u " + " LEFT JOIN user_role ur ON ur.user_id = u.id " + " LEFT JOIN department d ON u.dpt_id = d.id " + " WHERE (ur.role_id = #{roleId} or ur.role_id IS NULL) " + " <if test=\"keyword!=null and keyword!=''\"> AND (u.code like CONCAT(CONCAT('%',#{keyword}),'%') OR u.name like CONCAT(CONCAT('%',#{keyword}),'%')) </if>" + " </script> " }) List<RoleAuthVo> selectRoleAuthList(@Param("roleId") Integer roleId, @Param("keyword") String keyword); }
方式二 QueryDSL
service
package com.cebbank.api.service.impl; import com.cebbank.api.constant.AuthOrUnauthEnum; import com.cebbank.api.model.po.QDepartmentPo; import com.cebbank.api.model.po.QUserPo; import com.cebbank.api.model.po.QUserRolePo; import com.cebbank.api.model.po.UserRolePo; import com.cebbank.api.model.qo.RoleAuthQo; import com.cebbank.api.model.suo.AuthOrUnauthSuo; import com.cebbank.api.model.vo.PageVo; import com.cebbank.api.model.vo.RoleAuthVo; import com.cebbank.api.repository.UserRoleRepository; import com.cebbank.api.service.RoleAuthService; import com.cebbank.api.utils.GetDifferenceListUtil; import com.google.common.collect.Lists; import com.querydsl.core.Tuple; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.Projections; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @Slf4j @Service public class RoleAuthServiceImpl implements RoleAuthService { @Autowired private JPAQueryFactory jpaQueryFactory; @Autowired private UserRoleRepository userRoleRepository; /** * 默认查询-根据role_id查询 * * @param qo * @return */ @Override public PageVo<RoleAuthVo> authPageList(RoleAuthQo qo) { QUserRolePo userRolePo = QUserRolePo.userRolePo; QUserPo userPo = QUserPo.userPo; JPAQuery<Tuple> finalQuery = jpaQueryFactory.select(userRolePo.id, userRolePo.roleId, userPo.id, userPo.code, userPo.name) .from(userRolePo, userPo) .where(userRolePo.userId.eq(userPo.id).and(userRolePo.roleId.eq(qo.getRoleId()))) .offset((qo.getPageNo() - 1) * qo.getPageSize()) .limit(qo.getPageSize()); long total = finalQuery.fetchCount(); List<Tuple> fetch = finalQuery.fetch(); List<RoleAuthVo> roleAuthVos = fetch.stream().map(tuple -> { return RoleAuthVo.builder() .id(tuple.get(userRolePo.id)) .roleId(tuple.get(userRolePo.roleId)) .userId(tuple.get(userPo.id)) .userCode(tuple.get(userPo.code)) .userName(tuple.get(userPo.name)) .build(); }).collect(Collectors.toList()); PageVo<RoleAuthVo> pageVo = new PageVo<>(); pageVo.setTotal(total); pageVo.setList(roleAuthVos); return pageVo; } /** * 根据keyword搜索 * * @param qo * @return */ @Override public PageVo<RoleAuthVo> authList(RoleAuthQo qo) { QUserPo userPo = QUserPo.userPo; QUserRolePo userRolePo = QUserRolePo.userRolePo; QDepartmentPo departmentPo = QDepartmentPo.departmentPo; List<Predicate> predicates = Lists.newArrayListWithExpectedSize(10); if (StringUtils.isNotEmpty(qo.getKeyword())) { String likeStr = "%" + qo.getKeyword() + "%"; predicates.add(userPo.code.like(likeStr).or(userPo.name.like(likeStr))); } predicates.add(userRolePo.roleId.eq(qo.getRoleId()).or(userRolePo.roleId.isNull())); /*StringExpression stringExpression = new CaseBuilder() .when(userRolePo.roleId.isNotNull()) .then("Y") .otherwise("N").as("isAuth");*/ JPAQuery<RoleAuthVo> selectFromService = jpaQueryFactory.select(Projections.bean(RoleAuthVo.class, userRolePo.id.as("id"), userRolePo.roleId.as("roleId"), userPo.id.as("userId"), userPo.code.as("userCode"), userPo.name.as("userName"), userPo.dptId.as("deptId"), departmentPo.name.as("deptName") )).from(userPo); JPAQuery<RoleAuthVo> finalQuery = selectFromService .leftJoin(userRolePo).on(userRolePo.userId.eq(userPo.id)) .leftJoin(departmentPo).on(userPo.dptId.eq(departmentPo.id)) .where(predicates.toArray(new Predicate[]{})); List<RoleAuthVo> roleAuthVos = finalQuery.fetch(); roleAuthVos.forEach(roleAuthVo -> { if (Objects.nonNull(roleAuthVo.getRoleId())) { roleAuthVo.setIsAuth("Y"); } else { roleAuthVo.setIsAuth("N"); } }); long total = finalQuery.fetchCount(); PageVo<RoleAuthVo> pageVo = new PageVo<>(); pageVo.setTotal(total); pageVo.setList(roleAuthVos); return pageVo; } /** * 授权或取消授权 * * @param suo */ @Override @Transactional public void authOrUnauth(AuthOrUnauthSuo suo) { QUserRolePo userRolePo = QUserRolePo.userRolePo; String isAuth = suo.getIsAuth(); if (AuthOrUnauthEnum.AUTH.getIsAuth().equals(isAuth)) { // 授权 needAdd Integer roleId = suo.getRoleId(); List<UserRolePo> userRolePos = jpaQueryFactory.selectFrom(userRolePo) .where(userRolePo.roleId.eq(roleId)) .fetch(); List<Integer> databaseUserIds = userRolePos.stream().map(UserRolePo::getUserId).collect(Collectors.toList()); List<Integer> sourceIds = suo.getUserIds(); List<Integer> needAddIds = GetDifferenceListUtil.getDifferenceList(sourceIds, databaseUserIds); if (CollectionUtils.isNotEmpty(needAddIds)) { needAddIds.forEach(userId -> { UserRolePo po = new UserRolePo(); po.setRoleId(roleId); po.setUserId(userId); userRoleRepository.save(po); }); } log.info("授权成功"); } else { // 取消授权 Integer roleId = suo.getRoleId(); List<Integer> userIds = suo.getUserIds(); List<UserRolePo> userRolePos = jpaQueryFactory.selectFrom(userRolePo) .where(userRolePo.roleId.eq(roleId).and(userRolePo.userId.in(userIds))) .fetch(); userRoleRepository.deleteInBatch(userRolePos); log.info("取消授权成功:[" + userIds + "]"); } } }
repository
package com.cebbank.api.repository; import com.cebbank.api.model.po.UserRolePo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface UserRoleRepository extends JpaRepository<UserRolePo, Integer> { }
作者:习惯沉淀
如果文中有误或对本文有不同的见解,欢迎在评论区留言。
如果觉得文章对你有帮助,请点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
扫码关注一线码农的学习见闻与思考。
回复"大数据","微服务","架构师","面试总结",获取更多学习资源!