SpringBoot整合JPA数据库访问(增删改查)

在数据库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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
要在Spring Boot项目整合MyBatis框架实现增删改查操作,首先需要在项目的pom文件添加MyBatis Spring Boot Starter依赖。可以通过以下代码将依赖添加到pom文件: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> ``` 接下来,我们需要创建一个Spring Boot项目。可以使用Spring Initializr或其他方式创建一个基本的Spring Boot项目。 在创建完项目后,需要进行一些配置。可以在application.properties或application.yml文件配置数据库连接信息,如数据库URL、用户名、密码等。 接下来,需要创建实体类和Mapper接口。实体类对应数据库表的字段,Mapper接口定义了对应实体类的增删改查方法。 在Mapper接口,可以使用MyBatis的注解或XML文件配置SQL语句与方法的映射关系。可以使用@Insert、@Select、@Update、@Delete等注解定义SQL语句,并在方法调用这些注解。 最后,在Service层或Controller层调用Mapper接口的方法实现相应的增删改查操作。 这样就完成了在Spring Boot项目整合MyBatis框架实现增删改查操作的过程。通过配置依赖、数据库连接信息、创建实体类和Mapper接口、配置SQL语句,最后在Service或Controller层调用Mapper接口的方法,可以实现数据库增删改查操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Spring Boot整合Mybatis实现增删改查](https://blog.csdn.net/qq_45764233/article/details/127064407)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Spring boot整合Mybatis实现增删改查](https://download.csdn.net/download/weixin_42673574/87953723)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值