Java for Web Learning Notes (114): Spring Data (2) Warehouse interface __java

Source: Internet
Author: User
Tags iterable static class
Query Method

Crudrepository only defines the way to query through a primary key, which clearly does not meet the requirements. Spring provides a query method to solve such problems. Query methods include: Find ... by get ... by read ... By

will return a single result T, or multiple results iterable<t>, List<t>, collection<t>,page<t>. Here is an example:

Public interface Bookrepository extends Pagingandsortingrepository<book, long>{
    // Add three query methods outside the pagingandsortingrepository, corresponding to the unique key and key queries. Spring data is automatically implemented without the need to write any implementation code. Book
    FINDBYISBN (String ISBN);
    List<book> Findbyauthor (String author);
    List<book> Findbypublisher (String publisher);  
    Find ... By,by is followed by conditions, and find and by are generally of no particular significance, unless it is a specific meaning in the SQL statement 
    //The middle of the book is meaningless, but to the method name better semantics, equivalent to the FINDBYISBN () book
    FINDBOOKBYISBN (String ISBN); 
    This distinct as a reserved word has meaning, books meaningless, the equivalent of the select Distict * from the book Where publisher=. ,
    //assuming the table for entity mapping is book, property Publisher corresponds to the column name publisher
    list<book> Finddistinctbooksbypublisher (String Publisher); 
Both authors and publishers may have a lot of books that need to be paged out, and we'll instead:
Public interface Bookrepository extends Pagingandsortingrepository<book, long>{book
    FINDBYISBN (String ISBN );
    Page<book> Findbyauthor (String author, pageable instructions);
    Page<book> Findbypublisher (String Publisher, pageable instructions);
}
The entity attribute in the example above is either a simple type or a complex type, for example, Personentity contains address, and address has several attributes. We can also match specific address in the way described earlier, but if we only need to match an attribute in the address, such as a zip code. Can be written as:
List<person> Findbyaddresspostalcode (PostalCode code); Match the PostalCode attribute inside the address attribute, this kind of writing is apt to cause ambiguity, it is best to use underline way
page<person> Findbyaddress_postalcode (PostalCode Code, pageable instructions);
By following the placement of the query criteria, we specifically understand how to set:
➤by The default is equal to, is or equal, the following equivalent to the book FINDBYISBN (String ISBN);
Book Findbyisbnis (String ISBN);
Book Findbyisbnequal (String ISBN);
➤not,isnot expression is not equal to List<book> Findbyisbnisnot (Strign ISBN);
List<book> findbyisbnisnotequal (strign ISBN);
The conditional combination of ➤or and and and list<book> Findbyauthorandpublisher (string author, string publisher);
List<book> Findbyauthororpublisher (string author, string publisher); ➤ Case insensitive: Some columns in the database match are already set to ignore case, and we can explicitly declare them in the method. 
But from the query efficiency, we answer in the form design embodiment, for example, a key is case insensitive. 
Just publisher ignores case list<book> Findbyauthorandpublisherignorecase (string author, string publisher); Author and publisher ignore case list<book> Findbyauthorignorecaseandpublisherignorecase (string author, string 
Publisher); 
All uppercase and lowercase list<book> findbyauthorandpublisherallignorecase (string author, string publisher) are ignored;
➤after, Isafter,befor,isbefor for operation on time or date list<book> findbydatefoundedisafter (date date); ➤ for% processing: contains,containing, Iscontaining,startswith,startiNgwith, Isstartingwith,endswith,endingwith, Isendingwith//below corresponds to where title = '%value% ' list<book> findByTitleCo
Ntains (String value);
➤like: The following is equivalent to where title = ' value ', note that this is similar to contain, but the wildcard% is placed into value list<book> findbytitlelike (String value);
➤between,isbetween list<book> findbydatefoundedbetween (date start, date end);
➤exists: The equivalent of Exists//➤true,istrue,false,isfalse in sql: Checking the properties of a Boolean list<book> findbyapprovedisfalse (); ➤greaterthan,isgreaterthan,greaterthanequal,isgreaterthanequal,lessthan,islessthan,lessthanequal, Islessthanequal//➤in: Indicates that the value of the attribute must be equal to a value inside, and the iterable must be used to describe list<book> Findbyauthorin (iterable<string>
Authors); ➤null,isnull: The value is Null, the method should not have parameters, should be clearly expressed for the value of the//➤near, Isnear, Within, Iswithin is commonly used in NoSQL, not in the JPA use//➤regex,matchesregex , matches is used for regular expression list<book> Findbytitleregex (String regex);
a custom method

Spring data is powerful, but not necessarily completely covered by our needs, and in some cases we need a custom approach. to provide a custom method for a warehouse

1, we define a warehouse interface, which provides a way to define the customization.

Public interface Testrepositorycustom {
	list<testentity> Test (int page, int perpagenum, predicate ...) restrictions);
}

2. The warehouse interface of Spring data will extends interfaces with custom methods

Public interface Testrepository extends Crudrepository<testentity, long>,testrepositorycustom{
	testentity Findbyusername (String userName);

3, implement the custom method. Note that if this class does not need to add @repository, the class name must be scanned into testrepository after the Spring Data Warehouse interface plus impl,spring data. The Testrepositoryimpl will be found under the same package, and if so, will be specifically instantiated as a spring bean (that is, why we don't need to add @repository), we should implement the custom method here. There is no requirement for the name of the custom interface.

public class Testrepositoryimpl implements testrepositorycustom{
	@PersistenceContext private Entitymanager Entitymanager;

	@Override Public
	list<testpage> Test (int page, int numperpage, predicate ... restrictions) {
		//specific code ... .
	}
}
provide custom methods for all warehouses

This should be a very rare situation and we need to provide the same custom method for all warehouses.

1, the custom interface. Here extends the jparepository (which belongs to spring data, which extends Crudrepository and pagingandsortingrepository) so that spring data can be scanned. The tag @norepositorybean is to tell spring data not to generate an implementation for this interface, because it's just our generic custom interface, not the specific warehouse.

@NoRepositoryBean public
Interface customrepository<t, ID extends serializable> extends Jparepository<t, id>{public
    void Customoperation (T entity);
}

2. Provide implementation, we must inherit the base warehouse class Simplejparepository provided by spring data jap. Simplejparepository provides predefined interface methods, such as FindOne (ID), Save (T). If you need to supply QUERYDSL, you should extends replace with querydsljparepository.

public class customrepositoryimpl<t, ID extends serializable> extends
    T, Id> implements Customrepository<t, id>{private class<t> domainclass;

    Private Entitymanager Entitymanager; Public Customrepositoryimpl (class<t> domainclass, Entitymanager Entitymanager) {super (DomainClass, EntityMan
        Ager);
        This.domainclass = DomainClass;
    This.entitymanager = Entitymanager; Public Customrepositoryimpl (jpaentityinformation<t,?> Information,entitymanager EntityManager) {Supe
        R (Information, Entitymanager);
        This.domainclass = Information.getjavatype ();
    This.entitymanager = Entitymanager; public void Customoperation (T) {//code to implement custom operation}} 

3, let all warehouses support these customization methods. Since we tagged @norepositorybean,spring Data JPA does not automatically scan Customrepositoryimpl, we need to create a factory bean instead of the default factory bean to do this work, After the warehouse interface is scanned, the warehouse interface +impl is not implemented as its implementation, and is specified as Customrepositoryimpl.

public class Customrepositoryfactorybean<r extends Jparepository<t, id>, T,id extends Serializable> Jparepositoryfactorybean<r, T, id>{@Override protected Repositoryfactorysupport createrepositoryfactory (Ent
    Itymanager e) {return new customrepositoryfactory<t, id> (e);
        private static Class customrepositoryfactory<t, ID extends serializable> extends jparepositoryfactory{

        Private Entitymanager Entitymanager;
            Public customrepositoryfactory (Entitymanager Entitymanager) {super (Entitymanager);
        This.entitymanager = Entitymanager; @Override @SuppressWarnings ("unchecked") protected Object gettargetrepository (repositorymetadat A metadata) {return new customrepositoryimpl<t, id> (class<t>) Metadata.getdomaintype (), This.enti
        Tymanager); } @Override protected class<?> getrepositorybaseclass (RepositorymetadaTa metadata) {return customrepositoryimpl.class; }
    }
}
4, the default Jparepositoryfactorybean modified to Customrepositoryfactorybean
@EnableJpaRepositories (basepackages = "Cn.wei.flowingflying.chapter22.site.repositories",
    //returns the Factorybean class to is used for each repository instance. Defaults to Jparepositoryfactorybean.
    Repositoryfactorybeanclass = Customrepositoryfactorybean.class)


RELATED links: My professional Java for WEB applications related articles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.