【springboot——03】JPA 的操作
创始人
2025-05-31 20:41:19
0

目录

1.创建工程

2.配置数据库连接信息

3.构建实体数据表

4.创建接口和service层

5.创建控制层

6.整体项目 结构

7.运行项目 


1.创建工程

 

2.配置数据库连接信息

 jpa 默认采取 hibernate

server:port: 8888
spring:datasource:url: jdbc:mysql://localhost:3306/_spring_examdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: rootjpa:properties:hibernate:hbm2ddl:# hibernate 的配置属性: 自动创建、更新、验证数据表结构auto: update # create/create-drop/update/validatedialect: org.hibernate.dialect.MySQL5InnoDBDialectshow-sql: true # 开发工具的控制台显示 sqlthymeleaf:prefix: classpath:/templates/cache: false

3.构建实体数据表

 @NotEmpty 无法解析符号 'NotEmpty' 需要添加依赖

org.springframework.bootspring-boot-starter-validation
package com.example.jpa.entity;import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;/*** @author: fly* @Date: 2023-03-20 18:59* @Description: 使用 jpa 构建实体数据表*/
// 声明类为 实体
@Entity
//@Table(appliesTo = "article") 当类名与数据表名一致时,可省略
@Data
public class Article implements Serializable {@Id // 表名这是该类(表)的一个主键// IDENTITY 代表由数据库控制// AUTO 代表由 Spring Boot 应用程序统一管理【当有多个表时,id的自增值不一定从1开始】@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;// 指定字段名,如果字段名和列名相同可以省略@Column(nullable = false,unique = true,columnDefinition = "comment '文章标题'")@NotEmpty(message = "标题不能为空")private String title;// 枚举类型@Column(columnDefinition = "enum('图片','图文','文章')")private String type;// 文章类型private Boolean available = Boolean.FALSE;@Size(min=0,max=20)private String keyword;@Size(max=255)private String description;@Column(nullable = false)private String body;// 创建虚拟字段@Transientprivate List keywordLists;public List getKeywordLists() {return Arrays.asList(this.keyword.trim().split("|"));}public void setKeywordLists(List keywordLists) {this.keywordLists = keywordLists;}
}

运行项目 自动生成数据表

 

 

4.创建接口和service层

创建 ArticleRepository 继承 JpaRepository

package com.example.jpa.repository;import com.example.jpa.entity.Article;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;/*** @author: fly* @Date: 2023-03-21 9:25* @Description: 文章的持久化层*/
@Repository
public interface ArticleRepository extends JpaRepository, JpaSpecificationExecutor
{/*** 通过 文章 id 查询文章* @param id 文章id* @return 文章*/Article findById(long id); }

Service  层以及它的实现类

ArticleService 接口 

package com.example.jpa.service;import com.example.jpa.entity.Article;import java.util.List;/*** @author: fly* @Date: 2023-03-21 9:53* @Description:*/
public interface ArticleService {/*** 获取文章列表* @return 一组文章*/public List
getArticleList();/*** 通过 id 查找文章* @param id 文章 id* @return 文章*/public Article findArticleById(long id); }

 ArticleServiceImpl 实现类

package com.example.jpa.service.impl;import com.example.jpa.entity.Article;
import com.example.jpa.repository.ArticleRepository;
import com.example.jpa.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @author: fly* @Date: 2023-03-21 9:56* @Description: 文章 服务类*/
@Service
public class ArticleServiceImpl implements ArticleService {private ArticleRepository articleRepository;@Autowiredpublic void setArticleRepository(ArticleRepository articleRepository) {this.articleRepository = articleRepository;}/*** 获取所有文章* @return 所有文章*/@Overridepublic List
getArticleList() {return articleRepository.findAll();}/*** 通过 id 去查找文章* @param id 文章 id* @return 文章*/@Overridepublic Article findArticleById(long id) {return articleRepository.findById(id);} }

5.创建控制层

 ArticleController

package com.example.jpa.controller;import com.example.jpa.entity.Article;
import com.example.jpa.repository.ArticleRepository;
import lombok.extern.log4j.Log4j2;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;/*** @author: fly* @Date: 2023-03-21 8:24* @Description: 处理文章的控制器*/
@RestController
@RequestMapping("/article")
@Log4j2
public class ArticleController {private ArticleRepository articleRepository;@Autowiredpublic void setArticleRepository(ArticleRepository articleRepository) {this.articleRepository = articleRepository;}@RequestMapping("")public ModelAndView articleList(@RequestParam(value = "start",defaultValue = "0") Integer start,@RequestParam(value = "limit",defaultValue = "10") Integer limit) {start = start < 0 ? 0 : start;Sort sort = Sort.by(Sort.Direction.DESC,"id");Pageable pageable = PageRequest.of(start,limit,sort);Page
page = articleRepository.findAll(pageable);ModelAndView modelAndView = new ModelAndView("article/list");modelAndView.addObject("page",page);return modelAndView;}@RequestMapping("/{id}")public ModelAndView getArticle(@PathVariable Integer id) {Article article = articleRepository.findById(id);ModelAndView modelAndView = new ModelAndView("article/show");log.info(article);modelAndView.addObject("article",article);return modelAndView;} }

6.整体项目 结构

7.运行项目 

代码地址 

参考 GitHub 地址:GitHub - xiuhuai/Spring-Boot-Book

08 文件夹: jpa 操作数据库

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...