springboot jpa 单表动态查询


springboot jpa 单表动态查询

 

*************************

示例:根据name,age查询student,name或者age可能为null

 

******************

dao层

 

StudentRepository

public interface StudentRepository extends JpaRepository,
        JpaSpecificationExecutor {

}

 

CustomStudentRepository

@Repository
public class StudentPlusRepository {

    @Autowired
    private StudentRepository studentRepository;

    public List find(String name,Integer age){
        Specification specification= (Specification) (root, criteriaQuery, criteriaBuilder) -> {
            List predicates=new ArrayList<>();

            if(name!=null){
                predicates.add(criteriaBuilder.like(root.get("name"),name));
            }

            if(age!=null){
                predicates.add(criteriaBuilder.equal(root.get("age"),age));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        return studentRepository.findAll(specification);
    }
}

 

******************

controller层

 

StudentController

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private CustomStudentRepository customStudentRepository;

    @RequestMapping("/save")
    public String save(){
        for(int i=0;i<100;i++){
            Student student=new Student();
            student.setName("瓜田李下"+i);
            student.setAge(i%3);

            studentRepository.save(student);
        }

        return "success";
    }

    @RequestMapping("/get")
    public List get(){
        return customStudentRepository.find("瓜田李下"+"%",null);
    }

}

 

 

你可能感兴趣的:(jpa)