Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

sql - Search by many optional parameters in spring data jpa repository

So I have tables comment and author. I want to build complex search bar with many optional parameters. I want filter comments with optional author firstname/lastname and some flags like popularity(based on comment rating).

As I dont know how to write it using spring data jpa repository I ve been thinking on writing it as native query with @Query annotation, smth like this should work

Select c.* from comment c join author a on a.id = c.author_id
Where (:firstname = '' or (:firstname = a.firstname)) 
And (:lastname = '' or (:lastname = a.lastname))
And (:popular = false or (c.rating > 25))

Is there option to write it using spring data jpa?

In future I plan to add more parameters and pagination for example. Using spring it would be like 1 minute with sql query I will lost few hours.

Is there are some best practices in such cases?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest to use JpaSpecificationExecutor repository method findAll(Specification<T> spec, Pageable pageable). This solution allows you to extend the parameters list using the same repository and service API

Entities:

@Entity
@Table(name = "author")
public class Author {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @Column(name = "firstname")
    String firstname ;

    @Column(name = "lastname")
    String lastname ;

    // getters, setters, equals, hashcode, toString ...
}

@Entity
@Table(name = "comment")
public class Comment {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "author_id")
    Author author;

    @Column(name = "rating")
    Integer rating;

    // getters, setters, equals, hashcode, toString ...
}

Repository:

@Repository
public interface CommentRepository 
    extends JpaRepository<Comment, Long>, JpaSpecificationExecutor<Comment> {

}

Specifications: org.springframework.data.jpa.domain.Specification

public class CommentSpecs {

      /** if firstname == null then specification is ignored */
      public static Specification<Comment> authorFirstnameEquals(String firstname) {
        return (root, query, builder) -> 
             firstname == null ? 
                 builder.conjunction() :
                 builder.equal(root.get("author").get("firstname"), firstname);
      }

      /** if lastname == null then specification is ignored */
      public static Specification<Comment> authorLastnameEquals(String lastname) {
        return (root, query, builder) -> 
             lastname == null ? 
                 builder.conjunction() :
                 builder.equal(root.get("author").get("lastname"), lastname);
      }

      /** if rating == null then specification is ignored */
      public static Specification<Comment> ratingGreaterThan(Integer rating) {
        return (root, query, builder) -> 
             rating == null ? 
                 builder.conjunction() :
                 builder.greaterThan(root.get("rating"), rating);
      }
}

Service method parameters:

public class CommentParameters {

  String authorFirstname;
  String authorLastname;
  Integer rating;

  // getters, setters

}

All parameters are nullable. You can set the parameters you need only. If the parameter is null it is ignored by our specifications

Service:

@Service
public class CommentService {

  @Autowired
  CommentRepository repository;
                
  public List<Comment> getComments(CommentParameters params, Pageable pageable) {

      Specification spec1 = CommentSpecs.authorFirstnameEquals(params.getAuthorFirstname());                                            
      Specification spec2 = CommentSpecs.authorLastnameEquals(params.getAuthorLastname());
      Specification spec3 = CommentSpecs.ratingGreaterThan(params.getRating());

      Specification spec = Specifications.where(spec1).or(spec2).or(spec3);
                                                                    
      return repository.findAll(spec, pageable);

   }
}

I have written the code using a text editor, so it needs a revision. But I think the main point is easy to spot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...