Querydsl 简单语句格式

<!--query dsl -->

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-apt</artifactId>
</dependency>


<build>
    <plugins>
        <!--根据@Entity注解生成 对应 target 里面的entity对象
        QVoucher qVoucher = QVoucher.voucher;
        Long count =  queryFactory.delete(qVoucher).where(qVoucher.voucherId.eq(voucherId)).execute();-->
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>target/generated-sources/java</outputDirectory>
                        <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

 

 进行注入 EntityManager   和 事物管理:

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoApplication.class);
    }


    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}
# 子查询

QDepartment department = QDepartment.department;
QDepartment d = new QDepartment("d");
queryFactory.selectFrom(department)
    .where(department.size.eq(
        JPAExpressions.select(d.size.max()).from(d)))
     .fetch();


QEmployee employee = QEmployee.employee;
QEmployee e = new QEmployee("e");
queryFactory.selectFrom(employee)
    .where(employee.weeklyhours.gt(
        JPAExpressions.select(e.weeklyhours.avg())
            .from(employee.department.employees, e)
            .where(e.manager.eq(employee.manager))))
    .fetch();



# 更新修改

QCustomer customer = QCustomer.customer;
queryFactory.update(customer)
    .set(customer.name, "Bobby")
    .where(customer.name.eq("Bob"))
    .execute();

queryFactory.update(customer)
    .setNull(customer.name)
    .where(customer.name.eq("Bob"))
    .execute();



# 删除

QCustomer customer = QCustomer.customer;
queryFactory.delete(customer).execute();
queryFactory.delete(customer).where(customer.level.lt(3)).execute();



# 返回为 Tuple 类型的对象取值

# 1.
public List<Tuple> getOrdersListOnlinePaymentUnmatch() {
        QOrders qOrders = QOrders.orders;
        return hibernateQueryFactory
                .select(qOrders.ordersSn, qOrders.ordersAmount, qOrders.storeDiscountAmount, qOrders.couponAmount, qOrders.paymentTime)
                .from(qOrders)
                .fetch();
    }

# 2.
List<Tuple> orders = ordersDao.getOrdersListOnlinePaymentUnmatch();

# 3.获取第1个参数
orders.get(i).get(0, Long.class)

DTO

query = new JPASQLQuery<Void>(entityManager, templates);
List<CatDTO> catDTOs = query.select(Projections.constructor(CatDTO.class, cat.id, cat.name))
    .from(cat)
    .orderBy(cat.name.asc())
    .fetch();


public ServiceResponse<Object> selectCollection() {
        User user = ShiroKit.getUser();
        QProduct qProduct = QProduct.product;
        QCollection qCollection = QCollection.collection;
        List<ProductCollectionVo> list = jpaQueryFactory
                .select(Projections.bean(ProductCollectionVo.class,
                        qProduct.id,
                        qProduct.productName,
                        qProduct.productType,
                        qProduct.productDetails,
                        qProduct.produceBrand,
                        qProduct.produceMoney,
                        qProduct.produceBigimg,
                        qProduct.produceSmallimg,
                        qProduct.produceDetailsimg,
                        qCollection.id.as("collectionId")))
                .from(qProduct)
                .rightJoin(qCollection).on(qProduct.id.eq(qCollection.productId))
                .where(qCollection.userId.eq(user.getId())).fetch();
        return ServiceResponse.createBySuccess(list);


# 动态条件拼接查询
public void test() throws IOException {
        QCeshi qCeshi = QCeshi.ceshi;
        Predicate predicate = null;
        predicate = ExpressionUtils.and(predicate, qCeshi.name.eq("张三"));
        predicate = ExpressionUtils.and(predicate, qCeshi.id.eq(3));
        JPAQuery<Ceshi> where = jpaQueryFactory.selectFrom(qCeshi).where(predicate);

}
# 执行语句为
select ceshi from Ceshi ceshi where ceshi.name = ?1 and ceshi.id = ?2



NE : not equal 不等于 .ne
GE : greater than or equal 大于等于 .goe
LE : less than or equal 小于等于 .loe
GT : greater than 大于 .gt
LT : less than  小于 .lt
EQ : equal 等于 .eq

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Querydsl是一个Java开源框架,用于构建类型安全的SQL查询语句。它提供了一种使用API来构造查询语句的方式,而不是像传统的拼接字符串的方式。可以与Hibernate和JPA等框架结合使用。 在使用Querydsl执行SQL语句时,可以使用以下步骤: 1. 创建一个JPAQuery对象,传入EntityManager参数,例如:JPAQuery query = new JPAQuery(entityManager); 2. 构建查询语句,可以使用select、from、join、where等方法进行构造。例如,可以使用select方法来选择需要查询的字段,使用from方法来指定查询的表,使用join方法来进行表连接,使用where方法来添加查询条件。 3. 可以使用limit和offset方法来限制查询结果的数量和偏移量。 4. 最后,使用fetch方法来执行查询并获取结果。 以上是一个复杂查询的示例代码,通过使用Querydsl的API来构造查询语句,并使用fetch方法执行查询并获取结果。在这个例子中,使用了select方法选择需要查询的字段,使用from方法指定查询的表,使用leftJoin方法进行表连接,使用where方法添加查询条件,使用limit和offset方法限制查询结果的数量和偏移量。最后,使用fetch方法执行查询并获取结果,遍历结果并将其转化为Map对象进行输出。 通过使用Querydsl的API,可以更方便地构建类型安全的SQL查询语句,并避免了手动拼接字符串的方式带来的错误和不安全性。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [SQL查询构建工具Querydsl.zip](https://download.csdn.net/download/weixin_39840914/11371139)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [使用QueryDSL补充springDataJpa进行复杂动态sql语句进行sql查询 实现 关联 分页等功能](https://blog.csdn.net/u010838785/article/details/103954941)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值