整合Spring Data JPA操作数据及排序分页
一、 Sping Data JPA 简介
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套 JPA 应用框架,底层使用了 Hibernate 的 JPA 技术实现,可使开发者用极简的代码即可实现对数据的访问和操作。它提供了包括增删改查等在内的常用功能接口,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!
由于微服务系统的广泛应用,服务粒度逐渐细化,多表关联查询的场景一定程度减少。单表查询和单表的数据操作正是JPA的优势。
二、 将Spring Data JPA集成到Spring Boot
第一步:引入maven依赖包,包括Spring Data JPA和Mysql的驱动
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SpringBootComplete</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
第二步:修改application.yml,配置好数据库连接和jpa的相关配置
server:
port: 8089
spring:
#通用的数据源配置
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://123.57.87.54:3306/ssm?useSSL=false&useUnicode=true&characterEncoding=utf8
username: bms
password: bms@2018
jpa:
#这个参数是在建表的时候,将默认的存储引擎切换为 InnoDB 用的
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
#配置在日志中打印出执行的 SQL 语句信息。
show-sql: true
hibernate:
#配置指明在程序启动的时候要删除并且创建实体类对应的表
ddl-auto: validate
三、 基础核心用法
实体Model类
@Data
@Entity
@Table(name = "tt_user")
public class User {
public User(){
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String user_name;
// @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
private Date birthday;
private String sex;
private String address;
}
实现DAO层,数据操作接口
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
service层接口
public interface UserService {
// 查询所有
public List<User> findall();
/** 删除 */
public void delete(int id);
/** 增加*/
public void insert(User user);
/** 更新*/
public int update(User user);
/** 查询单个*/
public User selectById(int id);
/** 查询全部列表*/
public Iterator<User> selectAll(int pageNum, int pageSize);
}
service层接口实现
package com.dj.lunch.service;
import com.dj.lunch.dao.UserRepository;
import com.dj.lunch.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
/**
* 删除
*
* @param id
*/
@Override
public void delete(int id) {
userRepository.deleteById(id);
}
@Override
public List<User> findall(){
List<User> u = userRepository.findAll();
return u;
}
/**
* 增加
*
* @param user
*/
@Override
public void insert(User user) {
userRepository.save(user);
}
/**
* 更新
*
* @param user
*/
@Override
public int update(User user) {
userRepository.save(user);
return 1;
}
/**
* 查询单个
*
* @param id
*/
@Override
public User selectById(int id) {
Optional<User> optional = userRepository.findById(id);
User user = optional.get();
return user;
}
// @Override
// public Iterator<User> selectAll(int pageNum, int pageSize) {
// return null;
// }
/**
* 查询全部列表,并做分页
* @param pageNum 开始页数
* @param pageSize 每页显示的数据条数
*/
@Override
public Iterator<User> selectAll(int pageNum, int pageSize) {
//将参数传给这个方法就可以实现物理分页了,非常简单。
// Sort sort = new Sort.by(Sort.Direction.DESC, "id");
// Pageable pageable = new PageRequest(pageNum, pageSize, sort);
//2.2以上不适合此方法
Sort sort = Sort.by(Sort.Direction.DESC,"id");
PageRequest Page = PageRequest.of(pageNum,pageSize,sort);
Page<User> users = userRepository.findAll(Page);
Iterator<User> userIterator = users.iterator();
return userIterator;
}
}
实现Controller
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(method = RequestMethod.GET,value = "/delete/{id}")
public void delete(@PathVariable("id")int id){
userService.delete(id);
}
@RequestMapping(method = RequestMethod.GET,value = "/findall")
public List<User> findall(){
List<User> u = userService.findall();
return u;
}
@RequestMapping(method = RequestMethod.POST,value = "/insert")
public void insert(@RequestBody User user){
userService.insert(user);
}
@RequestMapping(method = RequestMethod.POST,value = "/update/{id}")
public void update(@RequestBody User user){
userService.update(user);
}
@RequestMapping(method = RequestMethod.GET,value = "/{id}/select")
public User select(@PathVariable("id")int id){
return userService.selectById(id);
}
@RequestMapping(method = RequestMethod.GET,value = "/selectAll/{pageNum}/{pageSize}")
public List<User> selectAll(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
Iterator<User> userIterator = userService.selectAll(pageNum, pageSize);
List<User> list = new ArrayList<>();
while(userIterator.hasNext()){
list.add(userIterator.next());
}
return list;
}
}
源码地址
参考链接:
https://www.jianshu.com/p/3b31270a44b1
https://www.kancloud.cn/hanxt/springboot2/1177605
I can feel you forgetting me。。 有一种默契叫做我不理你,你就不理我