Use Spring Data JPA
Add Maven dependency
1.9.0.RELEASE
5.0.1.Final
org.springframework.data
spring-data-jpa
${spring.data.version}
org.hibernate
hibernate-entitymanager
${hibernate.version}
Configure Spring Data JPA in Spring
The configuration of JPA and transactions is omitted here.
Use Spring Data JPA
To use Spring Data JPA, you only need to create an interface and inherit fromJpaRepositoryYou can.
public interface SystemUserRepository extends JpaRepository
{}
Test
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={classpath:applicationContext.xml})public class BaseSpringTestCase {}public class SystemUserRepositoryTest extends BaseSpringTestCase{ @Autowired private SystemUserRepository systemUserRepository; @Test public void testFindAll() { List
list = this.systemUserRepository.findAll(); assertNotNull(list); }}
Test page
@ Testpublic void testFindByPageable () {Pageable page = new PageRequest (1, 2); Page
PageList = this. systemUserRepository. findAll (page); // obtain the query result assertNotNull (pageList. getContent (); // obtain the total number of records assertTrue (pageList. getTotalElements ()> 0); // obtain the total number of pages assertTrue (pageList. getTotalPages ()> 0 );}
To implement paging, you only need to call
PageRequest has two parameters: page and pageSize. The page number starts from 0.
PageRequest (0, 10) queries records 1-10.
PageRequest (1, 10) queries the 11-20 records.
If the total number of records is less than the start row of the Data to be queried, Spring Data JPA will discard the SQL statement used to query the Data.
For example, if Table A has 6 records and PageRequest (1, 10) is used, no records can be found. Because the start position is 11, Spring will only execute the SQL statement to query the total number of records, instead of executing SQL statements to query data.