[Spring Data Repositories] study notes -- use existing repository and springrepository
The following are some notes about Spring Data Repositories in Spring-Data-mongoDB. Memo!
I feel that I am still familiar with official materials.
Spring Data Repositories objective: to reduce repeated persistent code.
Frequently Used repository interfaces,
Repository <-- CurdRepository <-- PagingAndSortingRepository
The last one is mainly used for paging and sorting.
Repository usage steps
1. Define the interface
public Interface PersonRepository extends Repository<User,Long>{...}
If we do not want to expose all methods inherited from Repository, we can use @ NoRepositoryBean to mark them.
@NoRepositoryBeanInterface MyBaseRepository<T,ID extends Serializable> extends Repository<T,ID>{T findOne(ID id);T save(T entity);}Interface UserRepository extends MyBaseRepository<User,Long>{User findByEmailAddress(EmailAddress emailAddress);}
In this way, there are only three methods in UserRepository.
2. Define methods for the interface defined above
List<Person> findByLastname(String lastname);
Spring can search by method name
public interface PersonRepository extends Repository<User,Long>{List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);List<Person> findByLastnameOrderByFirstnameAsc(String lastname);}
- AND, OR, Between, LessThan, GreaterThan, AND which operators are available in the databases used.
- IgnoreCase and AllIgnoreCase
- OrderBy (Asc or Desc)
Supports multi-level queries, such as using x.address.zip Code for search, available
List<Person> findByAddressZipCode(ZipCode zipCode);
Or
List<Person> findByAddress_ZipCode(ZipCode zipCode);
NOTE: If your attribute name contains _, such as first_name, two _ characters must be used to represent underscores.
3. Configure Spring for the interface (only xml is listed, and base-package is the package name of the Interface)
<jpa:repositories base-package="com.acme.repositories"/>
You can use include-filter/exclude-filter to filter interfaces.
<repositories base-package="com.acme.repositories"><context:exclude-filter type="regex" expression=".*SomeRepository"/></repositories>
4. Obtain the repository instance through injection and use it.
public class SomeClient {@Autowiredprivate PersonRepository repository;public void doSomething(){List<Person> persons = repository.findByLastname("Matthews");} }
Spring-data-mongodb
? 0 = key value in the Parameter
? 1 = value in the Parameter
How can I solve the errors in Appfuse20?