Fuzzy query
The use of Spring Data Jpa can reduce the developers' writing of SQL statements, and even do not need to write SQL statements at all. However, during the development process, there will always be various complex scenarios and pitfalls of all sizes.
A functional module in the project today requires fuzzy query. The fuzzy query keyword 'Like' in native SQL, and Spring Data Jpa's Repository interface also has Like corresponding to entity fields. But if you use it directly, then congratulations, you were lucky to have a pitfall.
Spring Data Jpa fuzzy query correct usage
First, we create an entity to store our data
/** * Entity* * @author chentai * @date 18/04/22 */@Data@Entity@EqualsAndHashCode(callSuper = true)public class ExampleEntity{ @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") private String Id ; private String username; private String deviceNames;}Next, create the Repository interface corresponding to our entity
/** * @author chentai * @date 18/04/22 */@Repositorypublic interface ExampleRepository extends CrudRepository<ExampleEntity, String> { /** * Correct usage of fuzzy query* Where username does not support fuzzy query, deviceNames supports fuzzy query* * @param deviceNames fuzzy query deviceNames * @param username Username Username * @return {@link List<ExampleEntity>} */ List<ExampleEntity> findAllByDeviceNamesContainingAndUsername(String deviceNames,String username); /** * Error usage of fuzzy query* where username does not support fuzzy query, deviceNames supports fuzzy query* * @param deviceNames Fuzzy query deviceNames * @param username Username Username* @return {@link List<ExampleEntity>} */ List<ExampleEntity> findAllByDeviceNamesLikeAndUsername(String deviceNames,String username); } Finally, we tested two methods in ExampleRepository in the test class (the test results are not displayed for the time being) and found that the findAllByDeviceNamesLikeAndUsername method did not correctly query the result we wanted, and the result obtained is the result of the exact query. And findAllByDeviceNamesContainingAndUsername gets the result of the fuzzy query we want.
Summarize
If you want to use fuzzy queries without writing SQL native statements in your project, please use the Containing keyword instead of taking it for granted that Like keywords are used natively. Like keywords are also used in JPA.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.