可以理解为JPA规范的再次封装抽象,底层还是使用了Hibernate的JPA技术实现,引用JPQL(Java Persistence Query Language)查询语言,属于Spring整个生态体系的一部分。随着Spring Boot和Spring Cloud在市场上的流行,Spring Data JPA也逐渐进入大家的视野,它们组成有机的整体,使用起来比较方便,加快了开发的效率,使开发者不需要关心和配置更多的东西,完全可以沉浸在Spring的完整生态标准实现下。JPA上手简单,开发效率高,对对象的支持比较好,又有很大的灵活性,市场的认可度越来越高。
JPA是Java Persistence API的简称,中文名为Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
JPA包括以下3方面的内容:
(1)一套API标准。在javax.persistence的包下面,用来操作实体对象,执行CRUD操作,框架在后台替代我们完成所有的事情,开发者从烦琐的JDBC和SQL代码中解脱出来。
(2)面向对象的查询语言:Java Persistence QueryLanguage(JPQL)。这是持久化操作中很重要的一个方面,通过面向对象而非面向数据库的查询语言查询数据,避免程序的SQL语句紧密耦合
依次点击 > 文件 > 新建 > 项目 如下图:
选择Spring Initializr项目 注意:创建springboot项目时需要网络
选择项目需要的依赖
我们直接创建就不选择了,创建完后直接在.xml文件里加入依赖,直接点击完成
首次创建springboot项目会加载一段时间
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.7.5
com.p
springbootjpa
0.0.1-SNAPSHOT
springbootjpa
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-data-jdbc
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-thymeleaf
com.mysql
mysql-connector-j
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
修改配置文件本文不使用application.properties文件而使用更加简洁的application.yml文件
在application.yml文件里面加入以下内容:
server:
port: 8080
#配置数据源 datasource
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/y2demo?serverTimezone=UTC
username: root
password: root
jpa:
database: mysql #指定你使用数据库
show-sql: true #展示sql语句
hibernate:
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
ddl-auto: update #自动
main:
allow-bean-definition-overriding: true
#swigger-ui配置
mvc:
pathmatch:
matching-strategy: ant_path_matcher
-- ----------------------------
-- Table structure for tb_customer
-- ----------------------------
DROP TABLE IF EXISTS `tb_customer`;
CREATE TABLE `tb_customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`telephone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`typeid` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `typeid`(`typeid`) USING BTREE,
CONSTRAINT `tb_customer_ibfk_1` FOREIGN KEY (`typeid`) REFERENCES `tb_customer_type` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 22 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tb_customer
-- ----------------------------
INSERT INTO `tb_customer` VALUES (1, '波波记', '不在不在bb', '15111356065', '娄底', 1);
-- ----------------------------
-- Table structure for tb_customer_type
-- ----------------------------
DROP TABLE IF EXISTS `tb_customer_type`;
CREATE TABLE `tb_customer_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tb_customer_type
-- ----------------------------
INSERT INTO `tb_customer_type` VALUES (1, '普通会员');
INSERT INTO `tb_customer_type` VALUES (2, '银卡会员');
INSERT INTO `tb_customer_type` VALUES (3, '金卡会员');
INSERT INTO `tb_customer_type` VALUES (4, '紫卡会员');
@Table(name = "tb_customer")
@Entity
@Data
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name",nullable = false,length = 20)
private String name;
@Column(name = "remark",nullable = false,length = 20)
private String remark;
@Column(name = "telephone",nullable = false,length = 20)
private String telephone;
@Column(name = "address",nullable = false,length = 20)
private String address;
@ManyToOne
@JoinColumn(name = "typeid")
private Type type;
}
//entity 表名即类名 属性名代表字段名
@Table(name = "tb_customer_type")
@Entity
@Data
public class Type {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String type_name;
}
@Repository
public interface CustomerRepository extends JpaRepository{
}
public interface CustomerService {
/**
* 查询用户数据
* @return
*/
List findAllCust();
/**
* 新增用户数据
* @param customer
*/
void insertCust(Customer customer);
/**
* 根据id删除用户数据
* @param id
*/
void deleteCust(Integer id);
/**
* 修改用户数据
* @param customer
*/
void updateCust(Customer customer);
/**
* 根据id查询用户数据
* @return
*/
Customer findById(Integer id);
/**
* 有条件的分页查询
*/
Page pageCust(Customer customer, Integer pageNum, Integer size);
}
@Service
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerRepository customerRepository;
@Override
public List findAllCust() {
return customerRepository.findAll();
}
@Override
public void insertCust(Customer customer) {
customerRepository.save(customer);
}
@Override
public void deleteCust(Integer id) {
customerRepository.deleteById(id);
}
@Override
public void updateCust(Customer customer) {
customerRepository.saveAndFlush(customer);
}
@Override
public Customer findById(Integer id) {
return customerRepository.getReferenceById(id);
}
@Override
public Page pageCust(Customer customer, Integer pageNum, Integer size) {
Integer id=customer.getId();
String name= customer.getName();
String remark=customer.getRemark();
String telephone=customer.getTelephone();
String address=customer.getAddress();
//构造器 参数
//创建匹配器,即如何使用查询条件,没有定义的作为=的方式查询,为空不作为条件
ExampleMatcher matcher=ExampleMatcher.matching() //构建对象
.withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("remark",ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("telephone",ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("address",ExampleMatcher.GenericPropertyMatchers.contains())
.withIgnorePaths("id"); //忽略属性:是否关注 因为是基本类型,需要忽略掉 创建时间和修改时间
//初始化实例
Example example=Example.of(customer,matcher);
if (pageNum==null||pageNum<0){
pageNum=0;
}
if (size==null){
size=2;
}
return customerRepository.findAll(example, Pageable.ofSize(size));
}
}
public class ResponseResult {
private Integer state;
private String msg;
private Object data;
public ResponseResult() {
this.state = 200;
this.msg = "成功";
}
public ResponseResult(Integer state, String msg) {
this.state = state;
this.msg = msg;
}
public ResponseResult(Integer state, String msg, Object data) {
this.state = state;
this.msg = msg;
this.data = data;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
@Controller
public class CustomerController {
@Autowired
private CustomerService customerService;
/**
* 查询用户信息
* @return
*/
@RequestMapping("/findAllCust")
@ResponseBody
public ResponseResult findAllCust(){
ResponseResult result=new ResponseResult();
try {
List all = customerService.findAllCust();
result.setState(200);
result.setMsg("成功");
result.setData(all);
return result;
}catch (Exception ex){
result.setState(500);
result.setMsg("失败"+ex.getMessage());
return result;
}
}
/**
* 删除用户信息
* @return
*/
@RequestMapping("/deleteCust")
@ResponseBody
public ResponseResult deleteCust(Integer id){
ResponseResult result=new ResponseResult();
try {
customerService.deleteCust(id);
result.setState(200);
result.setMsg("成功");
return result;
}catch (Exception ex){
result.setState(500);
result.setMsg("失败"+ex.getMessage());
return result;
}
}
/**
* 新增用户信息
* @return
*/
@RequestMapping("/addCust")
@ResponseBody
public ResponseResult addCust(Customer customer){
ResponseResult result=new ResponseResult();
try {
customerService.insertCust(customer);
result.setState(200);
result.setMsg("成功");
return result;
}catch (Exception ex){
result.setState(500);
result.setMsg("失败"+ex.getMessage());
return result;
}
}
/**
* 根据id查询用户信息
* @return
*/
@RequestMapping("/findById")
@ResponseBody
public ResponseResult findById(Integer id){
ResponseResult result=new ResponseResult();
try {
Customer customer=customerService.findById(id);
result.setState(200);
result.setMsg("成功");
result.setData(customer);
return result;
}catch (Exception ex){
result.setState(500);
result.setMsg("失败"+ex.getMessage());
return result;
}
}
/**
* 修改用户信息
* @param customer
* @return
*/
@RequestMapping("/updateCust")
@ResponseBody
public ResponseResult updateCust(Customer customer){
ResponseResult result=new ResponseResult();
try {
customerService.updateCust(customer);
result.setState(200);
result.setMsg("成功");
return result;
}catch (Exception ex){
result.setState(500);
result.setMsg("失败"+ex.getMessage());
return result;
}
}
/**
* 分页查询
* @param customer
* @return
*/
@RequestMapping("/pageCust")
@ResponseBody
public ResponseResult pageUser(Customer customer,Integer pageNum,Integer size){
ResponseResult result=new ResponseResult();
try {
Page all = customerService.pageCust(customer, pageNum, size);
result.setState(200);
result.setMsg("分页查询成功");
result.setData(all);
return result;
}catch (Exception ex){
result.setState(500);
result.setMsg("失败"+ex.getMessage());
return result;
}
}
@RequestMapping("/index.html")
public String toIndex(){
return "index";
}
}
@Controller
public class PageController {
/**
* 统一返回页面代码
* @param page
* @return
*/
@RequestMapping("/{page}.html")
public String toPage(@PathVariable("page")String page){
return page;
}
}
到这里就完成了增删改查以及条件分页操作,接下来我们对上面的代码在Postman中进行验证
其他就不测试了,也可在浏览器里测试,因为Postman挺方便,所有我用的Postman
前面已经导入了这两个maven包,如下
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
@SpringBootApplication
@EnableSwagger2
public class SpringbootjpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootjpaApplication.class, args);
}
}
开启后访问 http://localhost:8080/swagger-ui.html#/ 就可以访问swagger界面
package com.test.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
@Configuration
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(new DocumentationType("SWAGGER", "2.0"))
.apiInfo(getApiInfo())
// .host("http://localhost:8080")
.groupName("何灿")
//.globalResponseMessage(RequestMethod.GET, Lists.newArrayList())
//.pathMapping("AAAAA")// 上下文
.enableUrlTemplating(true)
.select()
.apis(RequestHandlerSelectors.basePackage("com.test.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo getApiInfo() {
Contact contact = new Contact("何灿", "https://gitee.com/hecanhc/dashboard/projects", "[email protected]");
return new ApiInfo("swagger文档", "描述", "2.0", "https://gitee.com/hecanhc/dashboard/projects",
contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
}
}