Spring data JPA Conditional paging query

Source: Internet
Author: User
Tags findone

PS: Half reproduced, half of their own use cases

Author: javaniu Link: https://www.zhihu.com/question/37873032/answer/73991650
Source: Know
Copyright belongs to the author, reprint please contact the author to obtain authorization. PS: Temporarily do not know the account number, so no contact with the original author, please forgive the original author. )

The query methods summarized by Springdata JPA are as follows: Findonebyname Query the User object by username Findallbylargethanid Query ID number is greater than the User object list with the specified parameter value, paging page returns Findallbyidandname Query ID and user name is equal to the specified parameter value of the user object, you can query the Findallbylikename fuzzy paging query user name through multiple predicate, like query Findallbyinids query specifies an ID collection user Object list Findallbyids A list of user ID objects specified through a native SQL query Findallbyname query for user objects with a user name equal to the specified value by using JPA query multiple sorting syntax: Sort sort = new sort (Direction.desc, "sort"). and (New sort (DIRECTION.DESC, "id"));

Package Com.zuidaima.springdata.service.impl;
Import java.util.ArrayList;

Import java.util.List;
Import Javax.annotation.Resource;
Import Javax.persistence.criteria.CriteriaBuilder;
Import Javax.persistence.criteria.CriteriaQuery;
Import Javax.persistence.criteria.Path;
Import Javax.persistence.criteria.Predicate;

Import Javax.persistence.criteria.Root;
Import Org.springframework.data.domain.Page;
Import Org.springframework.data.domain.PageRequest;
Import org.springframework.data.domain.Pageable;
Import Org.springframework.data.domain.Sort;
Import org.springframework.data.domain.Sort.Direction;
Import org.springframework.data.jpa.domain.Specification;

Import Org.springframework.stereotype.Service;
Import Com.zuidaima.springdata.entity.User;
Import Com.zuidaima.springdata.repository.UserRepository;

Import Com.zuidaima.springdata.service.UserService; /** * * @author javaniu 2013-06-04 22:27:23/@Service public class Userserviceimpl implements UserService {@Resourc E Public UsErrepository userrepository; @Override Public User findonebyname (final String name) {specification<user> specification = new SPECIFICATION&LT ; User> () {@Override public predicate topredicate (root<user> Root, criteriaquery<?> query, Criter
				Iabuilder criteriabuilder) {predicate _name = criteriabuilder.equal (Root.get ("name"), name);
			Return Criteriabuilder.and (_name);
		}
		};
	return Userrepository.findone (specification); @Override Public page<user> Findallbylargethanid (final Long ID, int Page, int count, sort sort) {specific ation<user> specification = new specification<user> () {@Override public predicate topredicate (Root<U ser> root, criteriaquery<?> query, Criteriabuilder criteriabuilder) {path<long> $id = Root.get ("I
				D ");
				predicate _id = CRITERIABUILDER.GT ($id, id);
			Return Criteriabuilder.and (_id);
		}
		}; pageable pageable = new Pagerequest (page-1, Count, sort);
		Return Userrepository.findall (specification, pageable); @Override Public User findallbyidandname (final Long ID, final String name) {specification<user> Specificatio n = new specification<user> () {@Override public predicate topredicate (root<user> Root, Criteriaque ry<?> query, Criteriabuilder criteriabuilder) {list<predicate> predicates = new Arraylist<predicate&gt
				;();
				path<long> $id = root.get ("id");
				predicate _id = Criteriabuilder.equal ($id, id);
				Predicates.add (_id);
				path<long> $name = root.get ("name");
				predicate _name = criteriabuilder.equal ($name, name);
				Predicates.add (_name);
			Return Criteriabuilder.and (predicates. ToArray (new predicate[] {}));
		}
		};
	return Userrepository.findone (specification); @Override Public page<user> findallbylikename (final String name, int Page, int count) {Specification<user
		> specification = new specification<user> () {	@Override public predicate topredicate (root<user> Root, criteriaquery<?> query, Criteriabuilder crite
				Riabuilder) {path<string> _name = root.get ("name");
				predicate _key = Criteriabuilder.like (_name, "%" + name + "%");
			Return Criteriabuilder.and (_key);
		}
		};
		Sort sort = new sort (DIRECTION.DESC, "id");
		pageable pageable = new Pagerequest (page-1, Count, sort);
	Return Userrepository.findall (specification, pageable); @Override Public page<user> findallbyinids (final list<long> IDs) {specification<user> Specificat Ion = new Specification<user> () {@Override public predicate topredicate (root<user> Root, Criteriaq
			uery<?> query, Criteriabuilder criteriabuilder) {return criteriabuilder.in (Root.get ("id")). Value (IDs);
		}
		};
		int page = 1;
		int count = Ids.size ();
		Sort sort = new sort (DIRECTION.DESC, "id");
		pageable pageable = new Pagerequest (page-1, Count, sort); Return UserrEpository.findall (specification, pageable);
	@Override public list<user> Findallbyids (list<long> IDs) {return userrepository.findallbyids (IDS);
	@Override public User findallbyname (String name) {return userrepository.findallbyname (name); }

}
=====================================  Gorgeous split line  ===============================================
The following are my practical applications in the project:
	1. Entity class: Gstest (no code here)
	2.Dao Layer:
	@Repository public
	Interface Gstestdao extends Jparepository<gstest, long>,jpaspecificationexecutor< gstest>{
	}
	3.Service layer: (can also be a separate parameter, see above for details), page: pages, Conut: Number of bars per page, sort: sorting
	Page<gstest> findonebyname (gstest gstest,int page,int count,sort Sort);
	4.ServiceImpl Layer
	The conditions for the page are age and name.
	@Override public
	page<gstest> findonebyname (final gstest gstest,int page,int count,sort Sort) {
		specification<gstest> specification = new specification<gstest> () {
			@Override public
			predicate Topredicate (root<gstest> Root,
					criteriaquery<?> query, Criteriabuilder criteriabuilder) {
				List <Predicate> predicates = new arraylist<predicate> ();
				Parameters are not null judgments. If not NULL, add this condition
				if (!gstest.getage (). IsEmpty ()) {
					predicate _age = criteriabuilder.equal (Root.get ("Age"), Gstest.getage ());
					Predicates.add (_age);
					System.out.println ("_age:" +gstest.getage (). IsEmpty ());
				predicate _name = criteriabuilder.equal (Root.get ("name"), Gstest.getname ());
				Predicates.add (_name);
				
				Return Criteriabuilder.and (_name);
				Return Criteriabuilder.and (Predicates.toarray (New predicate[]{}));
		
	4.controller: Control layer
	/**
		 *
		 * @param gstestdto entity, used to receive JSON type parameters
		 * @param
		 number of pages * @param pageSize
		 * @return 
  */
		@RequestMapping (value= "/fin", method = Requestmethod.post)
		@ResponseBody public
		page<gstest > findtest (@RequestBody gstestdto gstestdto, @RequestParam (value = "Page", defaultvalue = "1") int pagenumber,
				@ Requestparam (value = "Size", DefaultValue = constants.page_size_10) int pageSize) {gstest
			gstest = new Gstest (); 
  gstest=converterin.convertin (gstestdto);
			System.out.println ("Gstestdto:" +gstest);
			Sorted sort Sort
			= new sort (DIRECTION.ASC, "id");
			page<gstest> findonebyname = Gstestdaoservice.findonebyname (gstest,pagenumber,pagesize,sort);


			return findonebyname;
		}
	By this point, the conditional paging is complete. Look at the test results:
	I'm using Google's postman to test it:
	1. Reference:
  	{	 ' name ': ' Jak '
	}
	Results:
{  "content": [    {      "id": 3,       "properties_string": null,       "name": "Jak",       "Age": "",       "sex": "female",       "STA" Tus ":" 1 ",      " certime ":" 2013-05-11 09:00:00 "   },     {     " ID ": 4,      " properties_string ": null,      " name ":" Jak ",      " age ":" 21 " ,       "sex": "female",       "status": "1",       "certime": "2013-05-11 09:00:0 0 "   },     {     " id ": 5,      " properties_string ": null,   & nbsp   "name": "Jak",       "Age": "",       "sex": "female",       "status": "1
",      " certime ":" 2013-05-11 09:00:00 "   }  ],  " size ": 0,  " number ":   "Sort": [&nbsp    {      "direction": "ASC",       "property": "id",       "Ascending": True    }  ,   "LastPage": True,   "FirstPage": True,   "TotalPages": 1,   "Totalel Ements ": 3,  " numberOfElements ": 3}
	2. Pass the wrong parameter:
{
' name ': ' Jak ',
' age ': '} '
	Results:
{
"content": [],
"size": "Number
": 0,
"sort": [
{
"direction": "ASC",
' Property ': ' id ',
' ascending ': true
}
],
' lastpage ': true,
' FirstPage ': Tru E,
"TotalPages": 0,
"totalelements": 0,
"numberofelements": 0
}
	You can see the time when you can't find it. The content is a null value.
	To this, simple condition paging query is completed, I am also small white, improper place forgive me.

===============2017 year March 2 10:28:46=======  gorgeous split line  ===============================================
Note: Then the
entity class above: Prid
         entity class has a time attribute:
             private Date begintime;               
               Private Date Endtime;

JPA queries should be used when:
SimpleDateFormat sdf2 = new SimpleDateFormat ("Yyyy-mm-dd");
predicate duetime = Criteriabuilder.between (Root.<date>get ("Duetime"), Sdf2.parse (Prid.getBeginTime ()), Sdf2.parse (Prid.getendtime ()));

Note: Parse () returns a date-type data

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.