本帖最后由 miaoxiong 于 2019-7-2 21:30 编辑
QueryDsl
# Dsl概念
domain-specific language 特殊领域的计算机语言
常见的DSL有:HTML,Shell,make语言,ant语言,maven语言,rpm语言,dpkg语言,awk语言,正则表达式,dc计算机语言等,有些DSL语言又被称为微型语言
# QueryDsl概念
Unified Queries for Java.Querydsl is compact, safeand easy to learn.
针对Java的通用查询语言。它小巧、安全、易于学习。
Querydsl是一个Java开源框架用于构建类型安全的SQL查询语句。它采用API代替拼凑字符串来构造查询语句。可跟 Hibernate 和 JPA 等框架结合使用。
模块:
JPA、SQL、Mongodb、JDO、Lucene、Collections
# JPA集成
```xml
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
```
基本查询:
```java
JPAQuery query = new JPAQuery(entityManager);
List<Person> persons = query.from(person)
.where(
person.firstName.eq("John"),
person.lastName.eq("Doe"))
.list(person);
```
子查询:
```java
List<Person> persons = query.from(person)
.where(person.children.size().eq(
new JPASubQuery().from(parent)
.uniqueResult(parent.children.size().max())
)).list(person);
```
排序:
```java
List<Person> persons = query.from(person)
.orderBy(person.lastName.asc(),
person.firstName.desc())
.list(person);
```
多表连接:
```java
QCat cat = QCat.cat;
QCat mate = new QCat("mate");
QCate kitten = new QCat("kitten");
query.from(cat)
.innerJoin(cat.mate, mate)
.leftJoin(cat.kittens, kitten)
.list(cat);
```
分组:
```java
query.from(customer)
.groupBy(customer.lastName)
.list(customer.lastName);
```
查询类型:
```java
@Entity
public class Customer {
private String firstName;
private String lastName;
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public void setFirstName(String fn){
firstName = fn;
}
public void setLastName(String ln)[
lastName = ln;
}
}
```
QueryDsl会在Customer同目录下生成一个QCustomer类型。默认拥有一个实例:
```java
QCustomer customer = QCustomer.customer;
```
也可以指定自己的实例:
```java
QCustomer customer = new QCustomer("myCustomer");
```
|
|