Spring JPA 联表查询

简要背景说明:

  • 用户角色表 P_USER_ROLE和用户资料表 P_USER
  • 一个用户角色必定有一个用户资料,但多个用户角色可以共用一个用户资料
  • P_USER_ROLE 中USER_DATA_ID 为P_USER 的主键

需求:查询用户角色列表(含用户详细资料),所以在查询用户角色的同时,希望关联查询用户资料

实现步骤1/2:

在UserRole(P_USER_ROLE 的实体对象),增加User(P_USER的实体对象)属性,并生成get/set

/**
 * 用户资料
 */
private User user;
/**
 * 用户资料
 */
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "user_data_id", updatable = false, insertable = false, nullable = false)
public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

实现步骤2/2:

在原有分页查询条件Specification(查询P_USER_ROLE)中追加Specification查询条件(查询P_USER)

@Override
    public Page query(Map parameters, Long currentPage, Long pageSize) throws CodeException {
        List orders = OrderBuildable.create(parameters);
        Specification specification = SpecificationFactory.create(this.getGenericClass(), parameters).and(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                List predicates = new ArrayList<>();
                Join userJoin = root.join("user", JoinType.INNER);
                String nickName = (String) parameters.get("qry_like_nickName");
                if (StringUtils.isNotBlank(nickName)) {
                    predicates.add(criteriaBuilder.like(userJoin.get("nickName").as(String.class), "%" + nickName + "%"));
                }
                String name = (String) parameters.get("qry_like_name");
                if (StringUtils.isNotBlank(name)) {
                    predicates.add(criteriaBuilder.like(userJoin.get("name").as(String.class), "%" + name + "%"));
                }
                query.where((Predicate[]) predicates.toArray(new Predicate[0]));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        });
        int page = currentPage.intValue();
        if (page > 0) {
            --page;
        } else {
            page = 0;
        }
        PageRequest pageable;
        if (orders != null && !orders.isEmpty()) {
            pageable = PageRequest.of(page, pageSize.intValue(), Sort.by(orders));
        } else {
            pageable = PageRequest.of(page, pageSize.intValue());
        }
        return this.getRepository().findAll(specification, pageable);
    }

你可能感兴趣的:(spring,jpa)