在数据库springbootdata中创建t_article表和t_comment表,并插入数据。
数据库文件:
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 80030
Source Host : 127.0.0.1:3306
Source Database : springbootdata
Target Server Type : MYSQL
Target Server Version : 80030
File Encoding : 65001
Date: 2024-03-07 12:14:40
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_article
-- ----------------------------
DROP TABLE IF EXISTS `t_article`;
CREATE TABLE `t_article` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '文章id',
`title` varchar(200) DEFAULT NULL COMMENT '文章标题',
`content` longtext COMMENT '文章内容',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
-- ----------------------------
-- Records of t_article
-- ----------------------------
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
-- ----------------------------
-- Table structure for t_comment
-- ----------------------------
DROP TABLE IF EXISTS `t_comment`;
CREATE TABLE `t_comment` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '评论id',
`content` longtext COMMENT '评论内容',
`author` varchar(200) DEFAULT NULL COMMENT '评论作者',
`a_id` int DEFAULT NULL COMMENT '关联的文章id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb3;
-- ----------------------------
-- Records of t_comment
-- ----------------------------
INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '狂奔的蜗牛', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', 'tom', '1');
INSERT INTO `t_comment` VALUES ('3', '很详细', 'kitty', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '张三', '1');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张杨', '2');
INSERT INTO `t_comment` VALUES ('6', '很好', 'zxw', '2');
INSERT INTO `t_comment` VALUES ('7', '书本内容讲解清晰', 'zxw', '2');
INSERT INTO `t_comment` VALUES ('8', '全面且详细', 'zxw', '1');
INSERT INTO `t_comment` VALUES ('9', '全面且详细', 'zxw', '1');
INSERT INTO `t_comment` VALUES ('10', '全面且详细', 'zxw', '1');
INSERT INTO `t_comment` VALUES ('15', '全面且详细', 'zxw', '1');
增删改查操作
package com.example.experiment03;
import com.example.experiment03.pojo.Article;
import com.example.experiment03.pojo.Comment;
import com.example.experiment03.repository.ArticleRepository;
import com.example.experiment03.repository.CommentRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import java.util.List;
import java.util.Optional;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
@SpringBootTest
class Experiment03ApplicationTests {
@Test
void contextLoads() {
}
@Autowired
public CommentRepository commentRepository;
@Autowired
public Comment comment;
// id查询
@Test
public void selectComment(){
Optional<Comment> optional =commentRepository.findById(9);
if (optional.isPresent()){
System.out.println(optional.get());
}
}
// 查询author非空的commment评论集合
@Test
public void selectCommentByKeys(){
List<Comment> list =commentRepository.findByAuthorNotNull();
// for (Comment comment : list){
System.out.println(list);
}
// 查询comment 非空的commment评论集合
@Test
public void findByContentNotNull(){
List<Comment> list =commentRepository.findByContentNotNull();
System.out.println(list);
}
// 分页测试 查询文章编号a_id为1的评论
@Test
public void selectCommentPage(){
// 页面索引
// pageIndex = 1 为第二页
int pageIndex = 1;
// 每页数据条数
int pageSize =3;
// 排序方式
Sort.Direction sort =Sort.Direction.DESC;
// 分页器创建
Pageable pageable = PageRequest.of(pageIndex,pageSize,sort,"id");
List<Comment> commentPage =commentRepository.getCommentPage(1,pageable);
// 总页数
int totalPages =commentPage.size();
// 输出页面信息
System.out.println("当前页:"+(pageIndex+1)+",总页数:"+(totalPages));
commentPage.forEach(comment -> System.out.println(comment) );
}
@Test //修改
public void testUpdate(){
int count =commentRepository.updateComment("张敬桃",
"引人入胜,见解独到,值得一读。",1);
if (count>0){
System.out.println("更新成功");
}else {
System.out.println("更新失败");
}
}
@Test //删除
public void testDelete(){
int count =commentRepository.deleteComment(15);
if (count>0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}
@Test //添加
public void testInsert(){
comment.setId(17);
comment.setAuthor("李四");
comment.setContent("1234");
comment.setAId(1);
// save:id存在,执行update,不存在,执行insert
commentRepository.save(comment);
}
// exemple封装参数,精准查询
@Test
public void selectCommentByExemple(){
comment.setAuthor("张三");
Example<Comment> example =Example.of(comment);
List<Comment> list =commentRepository.findAll(example);
System.out.println(list);
}
// 模糊查询
@Test
public void selectCommentByExempleMatch(){
comment.setContent("很");
ExampleMatcher matcher =ExampleMatcher.matching().withMatcher("content",startsWith());
Example<Comment> example=Example.of(comment,matcher);
List<Comment> list =commentRepository.findAll(example);
System.out.println(list);
}
@Autowired
private ArticleRepository articleRepository;
@Test
// 在Java中,void是一种关键字,表示方法不返回任何值
// 查询所有文章信息,并显示评论内容
public void selectArticleAll(){
List<Article> articleList =articleRepository.findAll();
// 遍历输出列表
articleList.forEach(article -> System.out.println(article));
}
}
Comment实体类、CommentRepository接口
package com.example.experiment03.pojo;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.stereotype.Component;
@Data
@Component//getter tostring setter
@Entity(name = "t_comment")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String content;
private String author;
@Column(name = "a_id")
private Integer aId;
}
Article实体类、ArticleRepository接口
package com.example.experiment03.pojo;
import jakarta.persistence.*;
import lombok.Data;
import java.util.List;
@Data
@Entity(name = "t_article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String content;
// 查询时将子表查询出来
// 一对多关联关系,获取方式懒加载
@OneToMany(fetch = FetchType.EAGER)
// joinTable 关联表名
@JoinTable(name = "t_comment",joinColumns = {@JoinColumn(name = "a_id")},
inverseJoinColumns = {@JoinColumn(name = "id")})
private List<Comment> commentList;
}
若启动异常,则可能是SpringBoot整合JPA项目无法启动,properties文件未进行配置
properties文件
spring.application.name=Experiment03
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&useUnicode\
=true&characterEncoding=utf8
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
spring.datasource.druid.db-type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=20
spring.datasource.druid.min-idle=10
spring.datasource.druid.max-active=100
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.configuration.map-underscore-to-camel-case=true