亲宝软件园·资讯

展开

jpa EntityManager复杂查询

xieyuanqiu 人气:7

jpa EntityManager复杂查询

概念

接下来上代码啦!

1. 注入entitymanager

@PersistenceContext
private EntityManager em;

2. 建立连接,执行查询操作

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ADTO> q = cb.createQuery(ADTO.class);
Root<A> root = q.from(A.class);
/*********************表连接**************************/
Join<A, B> b = root.join("b", JoinType.LEFT);
Join<A, C> c = root.join("c", JoinType.LEFT);
Join<A, D> d = root.join("d", JoinType.LEFT);
Join<A, E> e = root.join("e",  JoinType.LEFT);
Join<A, F> f = root.join("f", JoinType.LEFT);
q.multiselect(//备注:ADTO要有对应构造函数哦
        root.get("id"),
        root.get("version"),
        root.get("code"),
        root.get("name"),
        root.get("isAlterable"),
        root.get("mustCharge"),
        root.get("isConsignment"),
        root.get("memo"),
        b.get("id"),
        b.get("name"),
        c.get("id"),
        c.get("description"),
        d.get("id"),
        d.get("name"),
        e.get("id"),
        e.get("name"),
        f.get("id"),
        f.get("name"),
        root.get("standardPrice"),
        root.get("upperPrice"),
        root.get("lowerPrice"),
        root.get("isActive")
);//还可以进行where.order by等操作哦
List<ADTO> rs = em.createQuery(q).getResultList();

到此就完成啦!!!

拓展

where条件

List<Predicate> predicates = new ArrayList<>();
CriteriaBuilder.In<String> in = cb.in(root.get("code").as(String.class));
for (String code: codes) {
    in.value(code);
}
predicates.add(in);
if (startDate != null && !"".equals(startDate)) {
    predicateList.add(cb.greaterThan(birthdayPath, startDate));
}
Predicate[] pre = new Predicate[predicates.size()];
q.where(predicates.toArray(pre));

or 条件拼接

public List<Predicate> getOrSearchPredicates(CriteriaBuilder cb, Root<T> root, String keywords){
        List<Predicate> predicates = new ArrayList<>();
        Predicate predicate = null;
        Predicate predicate1 = null;
        try {
            UUID uuid = UUID.fromString(keywords);
            predicate1 = cb.equal(root.get("id"), uuid);
        }catch (Exception e){
            log.info(e.getMessage());
        }finally {
            Predicate predicate2 = cb.like(root.get("code"), "%"+keywords+"%");
            Predicate predicate3 = cb.like(root.get("name"), "%"+keywords+"%");
            if (predicate1 != null){
                predicate = cb.or(predicate1, cb.or(predicate2,predicate3));
            } else {
                predicate = cb.or(predicate2, predicate3);
            }
        }
        predicates.add(predicate);
        return predicates;
}

JPA 动态更新

CriteriaBuilder cb=entityManager.getCriteriaBuilder();
CriteriaUpdate<T> op=cb.createCriteriaUpdate(clazz);
Root<T> root=op.from(clazz);
op.set(fieldName, value);
op.where(cb.equal(root.get(keyName), delta.get(keyName)));
entityManager.createQuery(op).executeUpdate();

基于EntityManager的使用

1、最基础的查询

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(User.class); //from User
cq.select(root); //select * from User
javax.persistence.criteria.Predicate pre = cb.equal(root.get("id").as(Integer.class),id);//id=1
cq.where(pre);//where id=1
Query query = entityManager.createQuery(cq);//select u from User u where u.id = 1
System.out.println(query.getResultList());

2、spring data jpa的toPredicate方法

public Predicate toPredicate(Root<RoleEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    List<Predicate> list = new ArrayList<Predicate>();
    list.add(cb.equal(root.get("dr").as(Integer.class), delete));
    if (StringUtils.isNotBlank(searchParam)) {/*searchParam 为传递参数*/
        list.add(cb.or(cb.like(root.get("roleName").as(String.class), cb.literal("%" + searchParam + "%")), cb.like(root.get("roleCode").as(String.class), cb.literal("%" + searchParam + "%"))));
    }
    // 角色id
    if (roleId != null && !("".equals(roleId.trim()))) {
        list.add(cb.equal(root.get("id").as(String.class), roleId));
    }
    // 管理员角色标识
    if (category != null && category > 0) {
        list.add(cb.equal(root.get("category").as(Integer.class), category));
    }
    //多角色Id
    if (roleids != null && roleids.size() > 0) {
        list.add(root.get("id").as(String.class).in(roleids));
    }
    Predicate[] predicates = new Predicate[list.size()];
    query.where(list.toArray(predicates));
    query.orderBy(cb.asc(root.get("roleType").as(String.class)), cb.asc(root.get("roleProperty").as(String.class)), cb.asc(root.get("roleCode").as(String.class)));
    return query.getRestriction();
}

参考 org.springframework.data.jpa.repository.support.SimpleJpaRepository 的 findAll方法,如下

public List<T> findAll(Specification<T> spec) {
    return getQuery(spec, (Sort) null).getResultList();
}
protected TypedQuery<T> getQuery(Specification<T> spec, Sort sort) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<T> query = builder.createQuery(getDomainClass());
    Root<T> root = applySpecificationToCriteria(spec, query);
    query.select(root);
    if (sort != null) {
        query.orderBy(toOrders(sort, root, builder));
    }
    return applyRepositoryMethodMetadata(em.createQuery(query));
}
private TypedQuery<T> applyRepositoryMethodMetadata(TypedQuery<T> query) {
    if (metadata == null) {
        return query;
    }
    LockModeType type = metadata.getLockModeType();
    TypedQuery<T> toReturn = type == null ? query : query.setLockMode(type);
    applyQueryHints(toReturn);
    return toReturn;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论