【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 操作数据库

相关内容

热门资讯

AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWR报告解读 WORKLOAD REPOSITORY PDB report (PDB snapshots) AW...
AWS管理控制台菜单和权限 要在AWS管理控制台中创建菜单和权限,您可以使用AWS Identity and Access Ma...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...
群晖外网访问终极解决方法:IP... 写在前面的话 受够了群晖的quickconnet的小水管了,急需一个新的解决方法&#x...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
Azure构建流程(Power... 这可能是由于配置错误导致的问题。请检查构建流程任务中的“发布构建制品”步骤,确保正确配置了“Arti...