SpringBoot Jpa模糊查询+分页

SpringBoot Jpa模糊查询+分页

在使用Jpa框架开发时遇到模糊查询还需要分页时,发现ExampleMatcher可以完成此功能的开发。

第一、建立实体类

其中的注解除了@Data、@Entity、@Table(name = “student”)必填,其他视情况添加

@Builder
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@SuppressWarnings("unused")
@Table(name = "student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ApiModelProperty(name = "id", value = "null")
    private Long id;
    
    @ApiModelProperty(name = "studentCode", value = "学生编码")
    private String studentCode;

    @ApiModelProperty(name = "studentName", value = "学生姓名")
    private String studentName;

    @ApiModelProperty(name = "studentPhone", value = "学生手机号")
    private String studentPhone;
}

第二、建立StudentRepository类

@Repository
public interface StudentRepository extends JpaRepository<Student,Long>, JpaSpecificationExecutor<Student> {
}

第三、在Controller类里写查询代码

下面对学生姓名进行模糊查询

@RestController
@RequestMapping("student")
public class StudentController extends PublicController {

    private final
    ClassInfoRepository classInfoRepository;

    public ClassInfoController(ClassInfoRepository classInfoRepository) {
        this.classInfoRepository = classInfoRepository;
    }
	@GetMapping("getListByUser")
    public ResponseEntity getListByClassCode(String studentName, Integer page, Integer size ){
    	//先判断user对象不为空
        if ( page == null || size == null ){
            return null;
        }
        
        if (!StringUtils.isEmpty(studentName)){
        	//这段代码才是模糊分页查询的关键
            Student student = new Student() ;
            student.setStudentName(studentName);
            //这段是模糊查询的关键ExampleMatcher.StringMatcher.CONTAINING
            ExampleMatcher exampleMatcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) ;
            studentPage = studentRepository.findAll(Example.of(student,exampleMatcher),PageRequest.of(page - 1, size)) ;
        }
        //ResultUnit需要自己定义
        return ResponseEntity.ok(ResultUnit.ok(studentPage)) ;
    }
 }

如果其他博友有其他的看法,欢迎评论区中指出。


版权声明:本文为weixin_43481812原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。