使用Criteria进行分组求和、排序、模糊查询的实例

 更新时间:2022年03月26日 11:01:30   作者:追月亮的猴子  
这篇文章主要介绍了使用Criteria进行分组求和、排序、模糊查询的实例,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Criteria进行分组求和、排序、模糊查询

工程框架使用的是spring data,但是spring data 提供的 JpaRepository 以及覆写JpaSpecificationExecutor接口并不能满足我的要求,我要进行模糊查询,并根据bookId对数量进行分组聚合,并获取数量最高的top n,由于模糊查询并不是必填条件,所以直接使用@Query注解感觉也不是很合适,于是采用Criteria来实现。

1.Entity如下

package com.example.springdatatest.repository.entity; 
import lombok.Data; 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Table
@Data
@Entity
public class TestEntity {
 
    @Id
    String testId;
 
    @Column
    public String regionCode;
 
    @Column
    public long count;
 
    @Column
    public String bookId; 
 
    @Column
    public String libraryCode;
}

2.repository如下

package com.example.springdatatest.repository; 
import com.example.springdatatest.repository.entity.TestEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 
public interface TestRepository extends JpaRepository<TestEntity,String>,JpaSpecificationExecutor {
}

3.service如下

package com.example.springdatatest.service; 
import com.example.springdatatest.repository.TestRepository;
import com.example.springdatatest.repository.entity.TestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
 
@Service
public class TestService {
 
    @Autowired
    TestRepository testRepository;
 
    @Autowired
    @PersistenceContext
    private EntityManager entityManager; 
 
    public void test(){
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class  ); 
        Root root = criteriaQuery.from(TestEntity.class);
 
        List<Predicate> predicateList = new ArrayList<>();
        predicateList.add(criteriaBuilder.equal( root.get("libraryCode" ), "1" ));
        predicateList.add(criteriaBuilder.like(root.get("regionCode"),"%"+"6101"+"%"));
        Predicate[] p = new Predicate[predicateList.size()];
        predicateList.toArray(p);
 
        Path bookId = root.get("bookId");
        Path bookCount = root.get("count"); 
        criteriaQuery.where(p)
                .multiselect(bookId,criteriaBuilder.sum(bookCount))
                .groupBy(bookId)
                .orderBy(criteriaBuilder.desc(criteriaBuilder.sum(bookCount)));
 
        List<Tuple> list = entityManager.createQuery(criteriaQuery).setFirstResult(1)
                .setMaxResults(1)
                .getResultList(); 
    }
}

4.顺便提及一个不经意间的小错误

也是由于粗心,没有写这一句  predicateList.toArray(p); ,导致一直报空指针异常。

java.lang.NullPointerException
    at org.hibernate.query.criteria.internal.predicate.CompoundPredicate.render(CompoundPredicate.java:166)
    at org.hibernate.query.criteria.internal.predicate.CompoundPredicate.render(CompoundPredicate.java:115)
    at org.hibernate.query.criteria.internal.predicate.CompoundPredicate.render(CompoundPredicate.java:105)
    at org.hibernate.query.criteria.internal.QueryStructure.render(QueryStructure.java:248)
    at org.hibernate.query.criteria.internal.CriteriaQueryImpl.interpret(CriteriaQueryImpl.java:292)
    at org.hibernate.query.criteria.internal.compile.CriteriaCompiler.compile(CriteriaCompiler.java:149)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3707)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:208)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
    at com.sun.proxy.$Proxy81.createQuery(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:309)
    at com.sun.proxy.$Proxy81.createQuery(Unknown Source)
    at com.example.springdatatest.service.TestService.test(TestService.java:50)
    at com.example.springdatatest.SpringdatatestApplicationTests.contextLoads(SpringdatatestApplicationTests.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

这只是实现的一个小demo,具体入参并没有体现,在此做一个记录。

Criteria进行模糊查询实现站内搜索功能

今天给网站新加入了一个站内搜索的功能,思想是:使用Criteria进行模糊查询。

Dao层的方法如下

//搜索方法
public List<Question> findSearch(String scon) {
        Session s =  getHibernateTemplate().getSessionFactory().openSession();
        Criteria criteria =s.createCriteria(Question.class);
        criteria.add(Expression.or(Expression.like("qdesc","%"+scon+"%"),Expression.like("qname","%"+scon+"%")));
        return criteria.list();
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 如何用Java模拟XN*2图灵机

    如何用Java模拟XN*2图灵机

    这篇文章主要介绍了如何用Java模拟XN*2图灵机方法,感兴趣的朋友可以参考下
    2021-04-04
  • Javacv使用ffmpeg实现音视频同步播放

    Javacv使用ffmpeg实现音视频同步播放

    这篇文章主要介绍了Javacv使用ffmpeg实现音视频同步播放,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • SpringBoot实现基于URL和IP的访问频率限制

    SpringBoot实现基于URL和IP的访问频率限制

    在现代 Web 应用中,接口被恶意刷新或暴力请求是一种常见的攻击手段,为了保护系统资源,需要对接口的访问频率进行限制,下面我们就来看看如何使用 Spring Boot 实现基于 URL 和 IP 的访问频率限制吧
    2025-01-01
  • Java实现将每日新闻添加到自己博客中

    Java实现将每日新闻添加到自己博客中

    这篇文章主要为大家详细介绍了Java如何实现将每日新闻添加到自己博客中并发送到微信群中,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-12-12
  • 关于RowBounds分页原理、RowBounds的坑记录

    关于RowBounds分页原理、RowBounds的坑记录

    这篇文章主要介绍了关于RowBounds分页原理、RowBounds的坑记录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • 详解Reactor中Context的用法

    详解Reactor中Context的用法

    在Reactor中提供了Context来替代ThreadLocal,可以实现一个跨线程的共享变量的透明方式。本文主要为大家介绍了Context的用法的用法,感兴趣的可以了解一下
    2023-02-02
  • Spring Boot通过Junit实现单元测试过程解析

    Spring Boot通过Junit实现单元测试过程解析

    这篇文章主要介绍了Spring Boot通过Junit实现单元测试过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • Java基本类型与byte数组之间相互转换方法

    Java基本类型与byte数组之间相互转换方法

    下面小编就为大家带来一篇Java基本类型与byte数组之间相互转换方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-08-08
  • Spring中@Async注解实现异步调详解

    Spring中@Async注解实现异步调详解

    在本篇文章里小编给大家分享的是关于Spring中@Async注解实现异步调详解内容,需要的朋友们可以学习下。
    2020-04-04
  • 浅谈idea中导入maven项目的两种方式

    浅谈idea中导入maven项目的两种方式

    本文主要介绍了浅谈idea中导入maven项目的两种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-08-08

最新评论