目录
1.创建工程
2.配置数据库连接信息
3.构建实体数据表
4.创建接口和service层
5.创建控制层
6.整体项目 结构
7.运行项目
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
@NotEmpty 无法解析符号 'NotEmpty' 需要添加依赖
org.springframework.boot spring-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;}
}
运行项目 自动生成数据表
创建 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);}
}
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;}
}
代码地址
参考 GitHub 地址:GitHub - xiuhuai/Spring-Boot-Book
08 文件夹: jpa 操作数据库
上一篇:静态版通讯录