Spring Boot整合MyBatis

该博客详细介绍了如何将Spring Boot与MyBatis整合。首先,搭建基础环境,包括创建数据库、表及填充数据,然后创建Spring Boot项目并初始化。接着,创建实体类Article和Comment。最后,编写配置文件,包括更改应用配置、添加数据源、定义映射器接口,并编写测试方法验证整合效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、搭建基础环境

1、先创建blog数据库然后创建相应的表

在这里插入图片描述

  • 在数据库里面创建文章表
CREATE TABLE `t_article` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章编号',
  `title` varchar(200) DEFAULT NULL COMMENT '文章标题',
  `content` longtext COMMENT '文章内容',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

  • 在文章表t_article里插入数据记录
    在这里插入图片描述
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('3', '安卓开发权威指南', '从入门到精通讲解...');
  • 然后继续创建评论表t_comment
    在这里插入图片描述

  • 向评论表t_comment插入数据
    在这里插入图片描述

INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '小明', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', '李文', '3');
INSERT INTO `t_comment` VALUES ('3', '很详细,喜欢', '童文宇', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '钟小凯', '2');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张三丰', '2');
INSERT INTO `t_comment` VALUES ('6', '操作性强,真棒', '唐雨涵', '3');
INSERT INTO `t_comment` VALUES ('7', '内容全面,讲解清晰', '张杨', '1');

2、创建Spring Boot项目MyBatisDemo并完成项目初始化工作
在这里插入图片描述
3、创建评论实体类 - Comment
在这里插入图片描述

package net.hy.lesson06.bean;

/**
 * 功能:评论实体类
 * 作者:黄运
 * 日期:2020年08月11日
 */
public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getaId() {
        return aId;
    }

    public void setaId(Integer aId) {
        this.aId = aId;
    }

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", aId=" + aId +
                '}';
    }
}

4、创建文章类 - Article
在这里插入图片描述

package net.hy.lesson06.bean;

import java.util.List;

/**
 * 功能:文章实体类
 * 作者:黄运
 * 日期:2021年05月10日
 */
public class Article {
    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<Comment> getCommentList() {
        return commentList;
    }

    public void setCommentList(List<Comment> commentList) {
        this.commentList = commentList;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", commentList=" + commentList +
                '}';
    }
}

二、编写配置文件

1、将全局配置文件application.properties更名为application.yaml然后进行数据库连接配置
在这里插入图片描述

# 配置数据库
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: zxcvbnm0147

    #配置Druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 20 #初始连接数
      min-idle: 10 #最小空闲连接数
      max-active: 100 #最大连接数

    #允许将下划线命名方法转成驼峰命名法(比如,a_id字段 -->aId属性)
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: net.hy.lesson06.bean

2、在pom.xml文件里添加阿里巴巴druid数据源

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>

3、创建评论映射器接口 - CommentMapper
在这里插入图片描述

package net.hy.lesson06.mapper;

import net.hy.lesson06.bean.Comment;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 功能:评论映射器接口
 * 作者:黄运
 * 日期:2021年05月10日
 */
@Mapper // 交给Spring容器管理
public interface CommentMapper {
    // 按照编号查询记录
    @Select("select * from t_comment where id = #{id}")
    Comment findById(Integer id);

    // 查找全部记录
    @Select("select * from t_comment")
    List<Comment> findAll();

    // 插入记录
    @Insert("insert into t_comment values(#{id}, #{content}, #{author}, #{aId})")
    int insertComment(Comment comment);

    // 更新记录
    @Update("update t_comment set content = #{content}, author = #{author} where id = #{id}")
    int updateComment(Comment comment);

    // 删除记录
    @Delete("delete from t_comment where id = #{id}")
    int deleteComment(Integer id);
}

4、编写测试方法testFindById()并运行
在这里插入图片描述

    @Test //测试查询全部记录的方法
    public void testFindAll() {
        List<Comment> comments = commentMapper.findAll();
        for (Comment comment : comments){
            System.out.println(comment);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值