springData使用QueryDsl的示例代码

时间:2021-05-19

经过多年,spring data jpa越来越完善,在版本迭代的过程中,会不断增加功能,今天看新的reference发现有Querydsl.然后搜索到上面的参考资料2

无论是JpaSpecificationExecutor,还是QueryDslPredicateExecutor,它俩都提供了使用Predicate(意义相同,都是构建where子句;类不同,javax.persistence.criteria.Predicate,com.querydsl.core.types.Predicate)去构建查询,使用比较方便.

关于两者的简单使用,上面的参考资料2有介绍.文末也有总结,从概括来看,我个人认为应倾向使用QueryDslPredicateExecutor,QueryDsl不仅适用于JPA repositories,还支持MongoDB.

下面是个例子

1.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://.mongodb.MongoClient;import org.exam.config.AppConfig;import org.exam.domain.Employee;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.geo.Circle;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.support.AnnotationConfigContextLoader;import java.net.UnknownHostException;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {AppConfig.class})public class MongoEmployeeRepositoryTest { @Autowired private MongoEmployeeRepository mongoEmployeeRepository; public static void main(String[] args) throws UnknownHostException { MongoTemplate template = new MongoTemplate(new MongoClient("127.0.0.1", 27017), "test"); Circle circle = new Circle(-73.99171, 40.738868, 0.01); System.out.println(); } @Test public void testFindAll() { Page<Employee> all = mongoEmployeeRepository.findAll(null, new PageRequest(0, 8)); for (Employee employee : all) { System.out.println("employee = " + employee); } }}

5.其它config.properties,logback.xml文件不太重要,篇幅关系就省略.

源码下载

再了解一下比较大的需求,从几张表来取几个字段的数据,返回分页排序数据.

1.在AppConfig注册JPAQueryFactory Bean

@Beanpublic JPAQueryFactory jpaQueryFactory(EntityManager entityManager) { return new JPAQueryFactory(new HQLTemplates(), entityManager);}

2.建一个DTO(数据传输对象)

public class UserDTO { private String empName; private String deptName; private long salary; //setter,getter略}

3.查询例子测试

private Page<UserDTO> findAll(String empName,Pageable pageable) { QEmployee qEmp = QEmployee.employee; QDepartment qDep = QDepartment.department; List<Predicate> criteria = new ArrayList<>(); if (StringUtils.hasText(empName)){ criteria.add(qEmp.name.eq(empName.trim())); } JPAQuery<?> query = jpaQueryFactory.from(qEmp).innerJoin(qDep).on(qEmp.deptId.eq(qDep.id)).where(criteria.toArray(new Predicate[criteria.size()])); long total = query.fetchCount(); List<UserDTO> content; if (pageable == null || total > pageable.getOffset()) { Map<String, SimpleExpression<?>> map = new HashMap<>(); map.put("deptName", qDep.name); map.put("empName", qEmp.name); map.put("salary", qEmp.salary); content = QuerydslUtils.applyPagination(pageable, query).select(Projections.bean(UserDTO.class, map)).fetch(); } else { content = Collections.emptyList(); } return new PageImpl<>(content, pageable, total);}@Testpublic void test() { Pageable pageable = new PageRequest(0, 10, new QSort(new OrderSpecifier<>(Order.DESC, QEmployee.employee.salary), new OrderSpecifier<>(Order.ASC, QDepartment.department.name))); Page<UserDTO> page = findAll("name", pageable); for (UserDTO userDTO : page) { System.out.println("userDTO = " + userDTO); }}

参考资料

1:http://docs.spring.io/spring-data/jpa/docs/1.10.x/reference/pdf/spring-data-jpa-reference.pdf

2:https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章