**
SpringBoot结合SpringJpa学习
首先加入pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
第二步,编辑application.properties文件:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_example?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC
spring.datasource.username=*****
spring.datasource.password=*****
# 此行解决@Column等标签无效的问题
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.jpa.show-sql = true
server.port=8089
第三步,添加repository的接口,让它继承org.springframework.repository包下面的接口:
import com.github.jpa.demo.entity.Person;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* PersonsReponsitory
* author BenJerry
* version 1.0
*/
public interface PersonsReponsitory extends PagingAndSortingRepository<Person, Long> {
}
第四步,在service层中注入上面所述接口的对象即可:
@Autowired
private PersonsReponsitory personsReponsitory;
@GetMapping(path = "/page")
@ResponseBody
public Page<Person> page() {
return personsReponsitory.findAll(PageRequest.of(1, 20));
}
实践结果:
{
"content": [],
"pageable": {
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"offset": 20,
"pageNumber": 1,
"pageSize": 20,
"paged": true,
"unpaged": false
},
"totalPages": 1,
"totalElements": 2,
"last": true,
"number": 1,
"size": 20,
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"numberOfElements": 0,
"first": false,
"empty": true
}