QueryDSL-findbyIdIn并做统计查询,提高效率

假设我的QContent文章实体类中infoSourceType是来源类型。

public Map findbyIds(List<String> ids){

    Predicate predicate1 = QContent.id.in(ids).and(QContent.infoSourceType.eq("微博"));
   
    //来源统计
    Long ins = queryFactory.select(QContent.id).where(predicate1).from(QContent).fetchCount();
    
    Map map = new HashMap();
    map.put("ins",ins);
    return map;
}

实现的sql语句为:

select count(id) from content ct
	where (ct.id in (100,1005,1006) and ct.info_source_type = "微博")
--	100,1005,1006是id列表
	

查询结果
查询结果

querydsl - jpa 5.0.0版本中,嵌套子查询可用于构建复杂的查询逻辑。以下是使用方法和示例: ### 使用方法 1. **创建实体类和对应的查询类型**:首先要有实体类,通过QueryDSL的APT工具生成对应的查询类型(Q类)。 2. **构建子查询**:在主查询中创建子查询对象,定义子查询的条件和投影。 3. **将子查询集成到主查询中**:可以将子查询作为条件、投影或连接的一部分。 ### 示例代码 假设存在两个实体类`Order`和`OrderItem`,它们的关系是一个订单可以包含多个订单项。以下是使用querydsl - jpa 5.0.0进行嵌套子查询的示例: ```java import com.querydsl.core.Tuple; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.jpa.impl.JPAQueryFactory; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.List; // 假设的实体类 class Order { private Long id; // 其他属性和方法 } class OrderItem { private Long id; private Order order; // 其他属性和方法 } // 对应的Q类(由QueryDSL APT生成) import static com.example.QOrder.order; import static com.example.QOrderItem.orderItem; public class NestedSubqueryExample { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("yourPersistenceUnit"); EntityManager em = emf.createEntityManager(); JPAQueryFactory queryFactory = new JPAQueryFactory(em); // 子查询:查找订单项数量大于2的订单ID com.querydsl.core.types.dsl.NumberPath<Long> subqueryCount = Expressions.numberPath(Long.class, "subqueryCount"); com.querydsl.jpa.JPAExpressions.select(orderItem.count()) .from(orderItem) .where(orderItem.order.id.eq(order.id)); // 主查询:查找订单项数量大于2的订单 Predicate condition = ExpressionUtils.gt(subqueryCount, 2L); List<Tuple> result = queryFactory.select(order.id, subqueryCount) .from(order) .where(condition) .fetch(); for (Tuple tuple : result) { Long orderId = tuple.get(order.id); Long itemCount = tuple.get(subqueryCount); System.out.println("Order ID: " + orderId + ", Item Count: " + itemCount); } em.close(); emf.close(); } } ``` 在上述示例中,首先创建了一个子查询,用于统计每个订单的订单项数量。然后将子查询的结果作为条件集成到主查询中,筛选出订单项数量大于2的订单。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值