简体   繁体   中英

Spring Data JPA Query string composing (query for very many or all fields)

With Spring Data JPA @Query it is very convient to write short declaration for a SQL query.

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.firstname like %?1")
  List<User> findByFirstnameEndsWith(String firstname);
}

and there is even Query By Example

Person person = new Person();                         
person.setLastname("Smith");                          
Example<Person> example = Example.of(person);
List<Person> results = personRepository.findAll(example);

But what approach should be used for general query composition? eg when using many fields or using several possible values for a field.

Before we had HSQL query string composing, and it feel natural, however I don't see a nice way to add this to Repository, which is Java Interface, bot Class.

Depending on your use case for each scenario, use all of what is available. I use query name for the simple ones (without @Query annotation), then I use @Query annotation for the more complex, I use QueryByExample for my searches, and lastly....

If you really need, you can create your own implementation of a repository. In here you can write your own HQL if you think that is the best approach. Some will tell you to not do this, as it will tie you to the use of Hibernate (but seriously, what are the odds of you actually changing ORM providers?)

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations

I actually do not see a good reason of using second way as the first way will be clear cut to write and also to understand. And also in the second way you will be needed to create an object set values then call the repository to find the people for you. It should find all the values that were inputted in the object and then do the processing. Instead define a query which will be operated only on the defined columns and give you the results. So first way itself makes more sense than the second one.

Thanks.

It's enough if your queries are simple. When them become complex and/or dynamic some other approach is needed.

Spring Data out of the box offers Specifications API which is a relatively simple way to specify predicates for queries.

The more powerful approach is Querydsl. It's advantage is type safety and code readability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM