This article simply describes exact matches (' where * = * ') in SQL, string search (' where * * like%name% ' in SQL).
If you need more advanced applications, you can refer to the Spring JPA official sample portal.
I. Preparatory work
1. Create a standard spring boot JPA program and configure the database connection
Pom.xml
... < Dependency > < groupId >org.springframework.boot</groupId> < Artifactid>spring-boot-starter-data-jpa</artifactid> </dependency> ...
2. Entity class User.java
... @Entity Public class User { @Id @GeneratedValue private Integer Id; Private String name; Private Short type; @Override public String toString () { return "user{" + "id=" + ID + ", name= '" + name + ' \ ' + ", type=" + Type + '} '; } // ... Setter/getter..}
3.Repository Userrepository.java
... Import org.springframework.data.jpa.repository.JpaRepository; Public Interface extends Jparepository<user, integer> {}
Two. Test program Userservice.java, run application to see results
@Component @transactional Public classUserService {Private Finaluserrepository userrepository; PrivateLogger Logger = Loggerfactory.getlogger ( This. GetClass ()); @Autowired PublicUserService (userrepository userrepository) { This. Userrepository =userrepository; //Initializing Datainit (); //Test Check NewPrintall ("Exact data lookup through Example", Querybyexample ()); Printall ("Match by Example string", Querybyexamplematcher ()); } Collection<User>querybyexample () {User User=NewUser (); User.settype (( Short) 1); Example<User> userexample =example.of (user); returnUserrepository.findall (userexample); } Collection<User>Querybyexamplematcher () {User User=NewUser (); User.setname ("10010"); Example<User> userexample = Example.of (User, Examplematcher.matching (). Withmatcher ("name", /*StartsWith, 10010% * endsWith,%10010 * contains * */ExampleMatcher.GenericPropertyMatchers.startsWith ())); returnUserrepository.findall (userexample); } voidPrintall (String Pre, collection<user>useriterator) {Logger.info ("Traverse user list {}", pre); for(User u:useriterator) {logger.info (u.tostring ()); } } voidinit () { for(inti = 0; i < 443; i++) {Userrepository.save (NewUser (("+" + i + "00111" + i), ( Short) (I% 3))); } } }
How to use the Eaxmple in SPRING-BOOT-STARTER-DATA-JPA