QueryDsl怎么在springData中使用
作者
本篇文章为大家展示了QueryDsl怎么在springData中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
1.pom.xml
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.exam</groupId> <artifactId>testjava</artifactId> <version>1.0.0</version> <name>${project.artifactId}</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring.version>4.2.5.RELEASE</spring.version> <spring-data.version>Hopper-SR1</spring-data.version> <querydsl.version>4.1.1</querydsl.version> <hibernate.version>5.1.0.Final</hibernate.version> <tomcat.version>8.0.32</tomcat.version> <logback.version>1.1.7</logback.version> <mysql.version>5.1.33</mysql.version> <junit.version>4.12</junit.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>${spring.version}</version> <scope>import</scope> <type>pom</type> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-releasetrain</artifactId> <version>${spring-data.version}</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <groupId>com.mysema.maven</groupId> <artifactId>maven-apt-plugin</artifactId> <version>1.0.4</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>process</goal> </goals> <configuration> <outputDirectory>target/generated-sources</outputDirectory> <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor> </configuration> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> </dependency> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <version>${querydsl.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> <version>${querydsl.version}</version> </dependency> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-mongodb</artifactId> <version>${querydsl.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>${tomcat.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> </dependencies> <repositories> <repository> <id>central</id> <name>CentralRepository</name> <url>http://repo1.maven.org/maven2</url> <layout>default</layout> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project>
2.Domain类
packageorg.exam.domain; importorg.springframework.data.mongodb.core.mapping.Document; importjavax.persistence.Column; importjavax.persistence.Entity; importjavax.persistence.Id; importjava.io.Serializable; @Entity @Document publicclassEmployeeimplementsSerializable{ @Id @Column(length=38) privateStringid; @Column(length=32) privateStringname; privatelongsalary; privatelongdepartmentId; //setter和getter略 }
3.Repository类
packageorg.exam.repository.jpa; importorg.exam.domain.Employee; importorg.springframework.data.querydsl.QueryDslPredicateExecutor; importorg.springframework.data.repository.PagingAndSortingRepository; importjava.util.Collection; publicinterfaceJpaEmployeeRepositoryextendsPagingAndSortingRepository<Employee,String>,QueryDslPredicateExecutor<Employee>{ Collection<Employee>findByIdIn(Collection<String>ids); }
packageorg.exam.repository.mongo; importorg.exam.domain.Employee; importorg.springframework.data.querydsl.QueryDslPredicateExecutor; importorg.springframework.data.repository.PagingAndSortingRepository; importjava.util.Collection; publicinterfaceMongoEmployeeRepositoryextendsPagingAndSortingRepository<Employee,String>,QueryDslPredicateExecutor<Employee>{ Collection<Employee>findByIdIn(Collection<String>ids); }
JPA有JpaRepository,MongoDB有MongoRepository,它俩都继承PagingAndSortingRepository
3.配置类
packageorg.exam.config; importcom.mongodb.MongoClient; importcom.mongodb.WriteConcern; importorg.apache.tomcat.jdbc.pool.DataSource; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.annotation.PropertySource; importorg.springframework.core.env.Environment; importorg.springframework.data.jpa.repository.config.EnableJpaRepositories; importorg.springframework.data.mongodb.MongoDbFactory; importorg.springframework.data.mongodb.core.MongoTemplate; importorg.springframework.data.mongodb.core.SimpleMongoDbFactory; importorg.springframework.data.mongodb.core.WriteResultChecking; importorg.springframework.data.mongodb.repository.config.EnableMongoRepositories; importorg.springframework.orm.jpa.JpaTransactionManager; importorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; importorg.springframework.orm.jpa.vendor.Database; importorg.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; importorg.springframework.transaction.PlatformTransactionManager; importorg.springframework.transaction.annotation.EnableTransactionManagement; importjavax.annotation.Resource; importjava.net.UnknownHostException; importjava.util.Properties; @Configuration @PropertySource("classpath:config.properties") @EnableTransactionManagement @EnableJpaRepositories(basePackages="org.exam.repository.jpa") @EnableMongoRepositories(basePackages="org.exam.repository.mongo") publicclassAppConfig{ @Resource privateEnvironmentenv; @Bean(destroyMethod="close") publicDataSourcedataSource(){ DataSourcedataSource=newDataSource(); dataSource.setDriverClassName(env.getProperty("ds.driverClassName")); dataSource.setUrl(env.getProperty("ds.url")); dataSource.setUsername(env.getProperty("ds.username")); dataSource.setPassword(env.getProperty("ds.password")); dataSource.setInitialSize(env.getProperty("ds.initialSize",Integer.class)); dataSource.setMinIdle(env.getProperty("ds.minIdle",Integer.class)); dataSource.setMaxIdle(env.getProperty("ds.maxIdle",Integer.class)); dataSource.setMaxActive(env.getProperty("ds.maxActive",Integer.class)); returndataSource; } @Bean publicLocalContainerEntityManagerFactoryBeanentityManagerFactory(){ HibernateJpaVendorAdapterjpaVendorAdapter=newHibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabase(Database.valueOf(env.getProperty("jpa.database"))); jpaVendorAdapter.setGenerateDdl(env.getProperty("jpa.generateDdl",Boolean.class)); jpaVendorAdapter.setShowSql(env.getProperty("jpa.showSql",Boolean.class)); LocalContainerEntityManagerFactoryBeanemf=newLocalContainerEntityManagerFactoryBean(); emf.setDataSource(dataSource()); emf.setPackagesToScan("org.exam.domain"); emf.setJpaVendorAdapter(jpaVendorAdapter); Propertiesproperties=newProperties(); properties.setProperty("hibernate.default_schema",env.getProperty("jpa.defaultSchema")); emf.setJpaProperties(properties); returnemf; } @Bean publicPlatformTransactionManagertransactionManager(){ returnnewJpaTransactionManager(entityManagerFactory().getObject()); } @Bean publicMongoDbFactorymongoDbFactory()throwsUnknownHostException{ returnnewSimpleMongoDbFactory(newMongoClient(env.getProperty("mongo.host"),env.getProperty("mongo.port",Integer.class)),env.getProperty("mongo.db")); } @Bean publicMongoTemplatemongoTemplate()throwsUnknownHostException{ MongoTemplatemongoTemplate=newMongoTemplate(mongoDbFactory()); mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION); mongoTemplate.setWriteConcern(WriteConcern.NORMAL); returnmongoTemplate; } }
4.测试类
packageorg.exam.repository.jpa; importorg.exam.config.AppConfig; importorg.exam.domain.Employee; importorg.junit.Test; importorg.junit.runner.RunWith; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.domain.Page; importorg.springframework.data.domain.PageRequest; importorg.springframework.test.annotation.Rollback; importorg.springframework.test.context.ContextConfiguration; importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner; importorg.springframework.test.context.support.AnnotationConfigContextLoader; importorg.springframework.transaction.annotation.Transactional; importjava.util.UUID; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader=AnnotationConfigContextLoader.class,classes={AppConfig.class}) @Transactional(transactionManager="transactionManager")//Rollback默认为true publicclassJpaEmployeeRepositoryTest{ @Autowired privateJpaEmployeeRepositoryjpaEmployeeRepository; @Test @Rollback(false) publicvoidtestSave(){ for(inti=0;i<5;i++){ Employeeemployee=newEmployee(); employee.setId(UUID.randomUUID().toString()); employee.setName("name"); employee.setDepartmentId(1+i); employee.setSalary(6800+i); jpaEmployeeRepository.save(employee); } } @Test publicvoidtestFindAll(){ Page<Employee>all=jpaEmployeeRepository.findAll(null,newPageRequest(0,8)); for(Employeeemployee:all){ System.out.println("employee="+employee); } } }
packageorg.exam.repository.mongo; importcom.mongodb.MongoClient; importorg.exam.config.AppConfig; importorg.exam.domain.Employee; importorg.junit.Test; importorg.junit.runner.RunWith; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.domain.Page; importorg.springframework.data.domain.PageRequest; importorg.springframework.data.geo.Circle; importorg.springframework.data.mongodb.core.MongoTemplate; importorg.springframework.test.context.ContextConfiguration; importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner; importorg.springframework.test.context.support.AnnotationConfigContextLoader; importjava.net.UnknownHostException; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader=AnnotationConfigContextLoader.class,classes={AppConfig.class}) publicclassMongoEmployeeRepositoryTest{ @Autowired privateMongoEmployeeRepositorymongoEmployeeRepository; publicstaticvoidmain(String[]args)throwsUnknownHostException{ MongoTemplatetemplate=newMongoTemplate(newMongoClient("127.0.0.1",27017),"test"); Circlecircle=newCircle(-73.99171,40.738868,0.01); System.out.println(); } @Test publicvoidtestFindAll(){ Page<Employee>all=mongoEmployeeRepository.findAll(null,newPageRequest(0,8)); for(Employeeemployee:all){ System.out.println("employee="+employee); } } }
5.其它config.properties,logback.xml文件不太重要,篇幅关系就省略.
源码下载
再了解一下比较大的需求,从几张表来取几个字段的数据,返回分页排序数据.
1.在AppConfig注册JPAQueryFactory Bean
@Bean publicJPAQueryFactoryjpaQueryFactory(EntityManagerentityManager){ returnnewJPAQueryFactory(newHQLTemplates(),entityManager); }
2.建一个DTO(数据传输对象)
publicclassUserDTO{ privateStringempName; privateStringdeptName; privatelongsalary; //setter,getter略 }
3.查询例子测试
privatePage<UserDTO>findAll(StringempName,Pageablepageable){ QEmployeeqEmp=QEmployee.employee; QDepartmentqDep=QDepartment.department; List<Predicate>criteria=newArrayList<>(); 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(newPredicate[criteria.size()])); longtotal=query.fetchCount(); List<UserDTO>content; if(pageable==null||total>pageable.getOffset()){ Map<String,SimpleExpression<?>>map=newHashMap<>(); 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(); } returnnewPageImpl<>(content,pageable,total); } @Test publicvoidtest(){ Pageablepageable=newPageRequest(0,10,newQSort(newOrderSpecifier<>(Order.DESC,QEmployee.employee.salary),newOrderSpecifier<>(Order.ASC,QDepartment.department.name))); Page<UserDTO>page=findAll("name",pageable); for(UserDTOuserDTO:page){ System.out.println("userDTO="+userDTO); } }
上述内容就是QueryDsl怎么在springData中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注恰卡编程网行业资讯频道。
目录
推荐阅读
0 条评论
本站已关闭游客评论,请登录或者注册后再评论吧~