Spring data supports hibernate-like query statements, as well as native SQL statements, which are documented in the typical example below.
/** * 1. repository is an empty interface . is a labeled interface * 2. if we define an interface that inherits repository, The interface is identified by the IOC container as a Repository Bean. * included in the IOC container . In this interface, you can define a method that satisfies a certain specification . * * 3. actually, can also be @RepositoryDefinition Annotations instead of inheritance Repository interfaces *//** * declaring methods in Repository subinterfaces * 1. Not a casual statement. . and need to conform to a certain specification * 2. Query method find | read | get start * 3. when a conditional query is involved, the properties of the condition are connected with the Conditional keyword * 4. be aware that the conditional attribute is capitalized in the first letter. * 5. cascading queries that support properties . if the current class has a qualifying attribute, the, instead of the cascading property . * if you need to use a cascading property, Use _ to connect between attributes. *///@RepositoryDefinition (domainclass=person.class,idclass= Integer.class) public interface personrepsotory extends jparepository<person, integer>,jpaspecificationexecutor<person>, persondao{//already defined privatE personrepsotory personrepsotory = ctx.getbean (personrepsotory.class);; /According to lastName to obtain the corresponding personperson getbylastname (string lastname);//person person = personrepsotory.getbylastname ("AA");//where lastname like ?% and id < ? List<person> getbylastnamestartingwithandidlessthan (string lastname, integer id);// List<person> persons = personrepsotory.getbylastnamestartingwithandidlessthan ("X", //where lastname like %? and id < List<person> getbylastnameendingwithandidlessthan (string lastname, integer id);// List<person> persons = personrepsotory.getbylastnameendingwithandidlessthan ("X", 10) ;//where email in (?, ?, ?) or birth < ? List<person> getbyemailinandbirthlessthan (list<string> emails, date birth);//persons = personrepsotory.getbyemailinandbirthlessthan ( Arrays.aslist ("[email protected]", "[email protected]", "[email protected]"), New date ());//where a.id > ? List<person> getbyaddress_idgreaterthan (integer id);//list<person> persons = personrepsotory.getbyaddress_idgreaterthan (1);//query id value the largest person//use @Query Annotations can be customized JPQL statements for a more flexible query @query ("Select p from person p where p.id = (Select max (p2.id) from person p2) Person getmaxidperson ();//Person person = personrepsotory.getmaxidperson ();//for @Query annotations The way the parameters are passed 1: use placeholders. @ Query ("select p from person p where p.lastname = ?1 and P.email = ?2 ") List<person> testqueryannotationparams1 (STRING&NBSP;LASTNAME,&NBSp String email);//list<person> persons = personrepsotory.testqueryannotationparams1 (" AA ", " [email protected]);//For @Query Annotate how parameters are passed 1: the way the named arguments . @Query ("Select p from person p where p.lastname = :lastname and p.email = :email ") List<person> testqueryannotationparams2 (@Param (" email ") String email, @Param ("LastName") string lastname);//list<person> persons = PERSONREPSOTORY.TESTQUERYANNOTATIONPARAMS2 ("[email protected]", "AA");//springdata allow adding on placeholders %%. @Query ("select p from person p where p.lastname like %? 1% or p.email like %?2% ") List<person> testqueryannotationlikeparam (String Lastname, string email);//list<person> persons = Personrepsotory.testqueryannotationlikeparam ("A", "BB");//springdata allows adding %%. @Query on placeholders ("select p from person p where p.lastname like %:lastname% or p.email like %:email% ") List<Person> TestQueryAnnotationLikeParam2 (@Param ("email") String email, @Param ("LastName") string lastname);//list<person> persons = personrepsotory.testqueryannotationlikeparam2 (" BB ", " A ");//settings nativeQuery=true that can use native SQL query @query (value=" Select count (ID) from jpa_persons ", nativequery=true) Long gettotalcount ();//long count = Personrepsotory.gettotalcount ()///Can be . by customizing the JPQL completion UPDATE and DELETE operations: JPQL does not support writing JPQL statements in @Query annotations using insert//, but must use @Modifying Modify . to notify SpringData, This is a UPDATE or DELETE action//update or delete operations require the use of transaction, at this time to define &NBsp service layer . Adds a transaction operation on the Service layer's method. //By default, there is a transaction on each method, springdata , But it's a read-only transaction . They can't complete the modification operation! @Modifying @query ("UPDATE&NBSP;PERSON&NBSP;P&NBSP;SET&NBSP;P.EMAIL&NBSP;=&NBSP;: Email where id = :id ") Void updatepersonemail (@Param (" id ") Integer id, @Param ("email") string email);//personrepsotory.updatepersonemail ("[email protected]", 1) ;//will throw exception, delete and modify to add transaction}
Delete and modify operations to add transactions, written in the service
First configure the automatic scan @servicepublic class Personservice {@Autowiredprivate personrepsotory personrepsotory; @Transactionalpublic void Savepersons (list<person> persons) {personrepsotory.save (persons);} @Transactionalpublic void Updatepersonemail (String email, Integer id) {personrepsotory.updatepersonemail (ID, email);}}
Paging and sorting, personrepository implementing Pagingandsortingrespository interface
@Testpublic void testpagingandsortingrespository () {//pageno starting from 0 . int The pageno = 6 - 1;int pagesize = 5;//pageable interface typically uses its pagerequest Implementation Class . which encapsulates the information that needs to be paged//sort-related . sort encapsulates the sort of information//order is specific to whether a property is ascending or descending . order Order1 = new order (direction.desc, "id"); Order order2 = new order ( direction.asc, "email"); Sort sort = new sort (ORDER1,&NBSP;ORDER2); Pagerequest pageable = new pagerequest (Pageno, pagesize, sort); Page<person> page = personrepsotory.findall (pageable); SYSTEM.OUT.PRINTLN ("Total number of records: " + page.gettotalelements ()); System.out.println ("current page: " + (Page.getnumber () + 1)); System.out.println ("Total pages: " + page.gettotalpages ()); System.out.println (" List: " on the current page + page.getcontent ()); System.out.println ("Number of records in the current page: " + page.getnumberofelements ());}
Jparepository interface
@Testpublic void Testjparepository () {Person person = new person ();p Erson.setbirth (New Date ());p erson.setemail ("[Email Protected] ");p erson.setlastname (" xyz ");p Erson.setid (28);//the record with ID 28 already exists in the database, execution Updateperson Person2 = Personrepsotory.saveandflush (person); System.out.println (person = = Person2);//false}
Jpaspecificationexecutor interface
/** * target: Implement conditions * * calls for paging . id > 5 with query criteria jpaspecificationexecutor 's page<t> findall (specification<t> spec, pageable pageable); * specification: encapsulates the query criteria for JPA Criteria queries * pageable: encapsulates the information requested for paging: such as pageno, pagesize, sort */@Testpublic void Testjpaspecificationexecutor () {int pageno = 3 - 1;int pagesize = 5; Pagerequest pageable = new pagerequest (pageno, pagesize);//usually use specification Anonymous inner class specification<person> specification = new specification<person> () {/** * @param *root: entity classes that represent queries . * @param query: from which you can Root object, tell JPA Criteria query which entity class to query . can also * to add query criteria, can also combine The   of the EntityManager object to get the final query; typedquery Object . * @param *cb: CriteriaBuilder object . for creating criteria Factory . for related objects of course you can get to Predicate objects * @return: *predicate types, Represents a query condition. */@Overridepublic predicate topredicate (Root<person> root, CRITERIAQUERY<?>&NBSP;QUERY,&NBSP;CRITERIABUILDER&NBSP;CB) {path path = root.get ("id "); PREDICATE&NBSP;PREDICATE&NBSP;=&NBSP;CB.GT (path, 5);return predicate;}}; Page<person> page = personrepsotory.findall (specification, pageable); SYSTEM.OUT.PRINTLN ("Total number of records: " + page.gettotalelements ()); System.out.println ("current page: " + (Page.getnumber () + 1)); System.out.println ("Total pages: " + page.gettotalpages ()); System.out.println (" List: " on the current page + page.getcontent ()); System.out.println ("Number of records in the current page: " + page.getnumberofelements ());}
Add a custom method to a repository
Steps:
-Define an interface: Declares the method to be added, and the self-implementation
-Provides the implementation class for this interface: the class name needs to be added Impl after the Repository to be declared, and the implementation method
-Declares the interface of the Repository interface, and inherits 1)
Use.
-Note: By default, Spring Data looks for "interface name Impl" as the implementation class in Base-package. You can also declare suffixes by Repository-impl-postfix.
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/74/DF/wKiom1Ys2LriUN0RAAE-IPPUMdc300.jpg "title=" 1111. JPG "alt=" wkiom1ys2lriun0raae-ippumdc300.jpg "/>
Persondao interface
public interface Persondao {void Test ();
Personrepsotoryimpl class implements Persondao interface
public class Personrepsotoryimpl implements Persondao {@PersistenceContextprivate Entitymanager entitymanager;@ overridepublic void Test () {Person person = Entitymanager.find (Person.class, 11); System.out.println ("--" + person);}}
The Personrepsotory interface inherits the Persondao interface and can use a custom method
Test
@Testpublic void Testcustomrepositorymethod () {personrepsotory.test ();}
Add a self-implementing method for all Repository
Steps:
-Declares an interface that declares a method that needs to be customized, and that the interface needs to inherit the Repository of Spring Data.
-Provides 1) the implementation class for the declared interface. and inherit Simplejparepository, and provide the implementation of the method
-Define the Jparepositoryfactorybean implementation class to make it 1) defines the object of the interface implementation class
-Modify the full class name of the Factory-class property of the <jpa:repositories/> node to point to 3)
-Note: The global extension implementation class does not use IMP as the suffix or add @NoRepositoryBean annotations to the global expansion interface to inform Spring data:spring Data not to be used as Repository
This article is from "Avatar" blog, please make sure to keep this source http://shamrock.blog.51cto.com/2079212/1706098
Spring Data Learning Note-Query method