Appending custom conditions on spring data jpa repository method queries

后端 未结 2 2050
梦如初夏
梦如初夏 2021-02-04 19:46

Short Version

I am looking for a way to have all the findBy methods of a repository class appended with a particular condition

Full Vers

2条回答
  •  攒了一身酷
    2021-02-04 20:06

    You can use Predicate of QueryDSL (or Specification) in Spring Data JPA methods.

    Example:

    interface UserRepository extends CrudRepository, QueryDslPredicateExecutor {
    }
    
    Predicate predicate = QUser.user.firstname.equalsIgnoreCase("dave")
        .and(user.lastname.startsWithIgnoreCase("mathews"));
    
    userRepository.findAll(predicate);
    

    To work with QueryDSL add to you pom.xml:

    
    //..
        
            com.querydsl
            querydsl-jpa
            4.1.4
            
                
                    org.slf4j
                    slf4j-api
                
            
        
        
            com.querydsl
            querydsl-apt
            4.1.4
            provided
        
    
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
    
            
                com.mysema.maven
                apt-maven-plugin
                1.1.3
                
                    
                        
                            process
                        
                        
                            target/generated-sources
                            com.querydsl.apt.jpa.JPAAnnotationProcessor
                        
                    
                
            
        
    
    

    Then compile your project and you will get Q-classes of your entities. More info is here.

提交回复
热议问题