jpa EntityManager 復雜查詢實例

jpa EntityManager復雜查詢

概念

  • EntityManager:EntityManager是JPA中用於增刪改查的接口,它的作用相當於一座橋梁,連接內存中的java對象和數據庫的數據存儲。可以用getCriteriaBuilder()的方式獲取CriteriaBuilder對象。
  • CriteriaBuilder接口:用於構造標準查詢、復合條件、表達式、排序等。可以通過createQuery的方式獲取CriteriaQuery實例。
  • CriteriaQuery接口:代表一個specific的頂層查詢對象,它包含著查詢的各個部分,比如:select 、from、where、group by、order by。
  • Root接口:代表Criteria查詢的根對象,定義瞭實體類型,能為將來導航獲得想要的結果,它與SQL查詢中的FROM子句類似

接下來上代碼啦!

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;
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: