springboot jpa 리스트 동적 조회

2051 단어 jpa
springboot jpa 리스트 동적 조회
 
*************************
예:name,age에 따라student,name 또는age가null일 수 있습니다
 
******************
다오층
 
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);
    }

}

 

좋은 웹페이지 즐겨찾기