jpa动态sql

1.EntityManager

group by 指定字段

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery query = cb.createTupleQuery();
Root root = query.from(Student.class);

List predicates = Lists.newArrayList();
predicates.add(cb.in(root.get("status")).value(Lists.newArrayList(0, 1)));
if (StringUtils.isNotBlank(name)) {
    predicates.add(cb.like(root.get("name"), "%" + name + "%"));
}

CriteriaQuery criteriaQuery = query.select(cb.tuple(root.get("name"), root.get("id"))).where(predicates.toArray(new Predicate[0])).groupBy(root.get("name"), root.get("id"));
entityManager.createQuery(criteriaQuery).getResultList();

2.query dsl

QStudent student = QStudent.Student;
jpaQueryFactory.selectFrom(student).where(student.name.eq("lucy")).fetchFirst();

以上两种是定义DAO的实现类。在实现类中写查询方法,第一种需要注入EntityManager,第二种需要注入JpaQueryFactory。

下面在接口中写动态sql

3.JpaSpecificationExecutor

// duty 包含 post ,post 包含 department
default List list(String start, String end, Collection departments, Collection names) {
    return this.findAll((Specification) (root, query, cb) -> {
        List predicates = Lists.newArrayList();
        predicates.add(cb.equal(root.get("flag"), true));
        if (StringUtils.isNotBlank(start)) {
            predicates.add(cb.greaterThanOrEqualTo(root.get("date"), start));
        }
        if (StringUtils.isNotBlank(end)) {
            predicates.add(cb.lessThanOrEqualTo(root.get("date"), end));
        }
        if (CollectionUtils.isNotEmpty(departments)) {
            predicates.add(cb.in(root.get("post").get("department")).value(departments));
        }
        if (CollectionUtils.isNotEmpty(names)) {
            predicates.add(cb.in(root.get("post").get("name")).value(names));
        }
        return cb.and(predicates.toArray(new Predicate[0]));
    });
}

4.QuerydslPredicateExecutor

default Iterable findByParams(String name, String telephone) {
    QStudent student = QStudent.student;
    BooleanBuilder builder = new BooleanBuilder();
    if (StringUtils.isNotBlank(name)) {
        builder.and(messageMember.name.like("%" + name + "%"));
    }
    if (StringUtils.isNotBlank(telephone)) {
        builder.and(messageMember.telephone.like("%" + telephone + "%"));
    }
    return this.findAll(builder);
}

代码结构

实现类和接口方式组合。下列接口StudentDao就具有了selectCustom方法

interface StudentDao extends StudentCustomDao, JpaRepository, JpaSpecificationExecutor, QuerydslPredicateExecutor {
    Page selectAll(Pageable of);

    default Student selectOne(Integer id){

    }

}



interface StudentCustomDao {
    Page selectCustom();
}

class StudentCustomDaoImpl implments StudentCustomDao {

    EntityManager entityManager;
    

    public Page selectCustom(){

    }

}

你可能感兴趣的:(jpa动态sql)