Springboot整合Mybatis框架(一):使用注解的方式整合Mybatis

基础环境搭建:

1.创建数据库表

  • 我们先创建一个Springbootdata数据库
  • 创建1.文章表t_article 2.评论表t_comment 两张数据库表
  • 往这两张表中插入数据
# 创建数据库
CREATE DATABASE springbootdata;
# 选择使用数据库
USE springbootdata;
# 创建表t_article并插入相关数据
DROP TABLE IF EXISTS `t_article`;
CREATE TABLE `t_article` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
  `title` varchar(200) DEFAULT NULL COMMENT '文章标题',
  `content` longtext COMMENT '文章内容',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
# 创建表t_comment并插入相关数据
DROP TABLE IF EXISTS `t_comment`;
CREATE TABLE `t_comment` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
  `content` longtext COMMENT '评论内容',
  `author` varchar(200) DEFAULT NULL COMMENT '评论作者',
  `a_id` int(20) DEFAULT NULL COMMENT '关联的文章id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
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');

2.生成一个Springboot项目

  • 先通过Spring Initializr方式创建一个Springboot项目(这里我们不演示如何创建Springboot项目了)

  • 创建对应着数据库springbootdata中表的实体类
    comment表:

public class Comment {//对应数据库中的Springbootdata——t_comment表
    private Integer id;
    private String content;
    private String author;
    private Integer aId;//关联ID

    public Comment() {
    }

    public Comment(Integer id, String content, String author, Integer aId) {
        this.id = id;
        this.content = content;
        this.author = author;
        this.aId = 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 +
                '}';
    }
}

Article表:

public class Article {对应数据库中的Springbootdata——t_article表
    //典型的一对多关系映射
    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;//Comment集合,

    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 +
                '}';
    }
}

  • 这时候我们使用第三方Druid连接池来对连接数据库的一些参数进行设置,需要先添加对应的依赖地址
		<!--配置Druid连接池的依赖-->
		<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
  • 然后在Springboot的配置文件中配置Druid连接池来对连接数据库的默认参数进行修改
spring:
  datasource:
    druid:
      url:  jdbc:mysql://localhost:3306/springbootdata
      driver-class-name:  com.mysql.jdbc.Driver
      username:  root
      password:  root
      initial-size:  20      #初始化连接数
      min-idle:  10         #最小空闲数
      max-active:  100      #最大连接数
  • 导入Mybatis依赖和MySQL的依赖
<!--Spring boot 整合MyBaties框架-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.1</version>
		</dependency>

		<!--配置mysql的依赖-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
		</dependency>

2.通过注解的方式来整合Mybatis

  1. 通过注解的方式编写Dao层业务
/**
 1. 这是整合Mybatis使用注解的形式开发
 */
@Mapper   //表示这是一个mapper接口文件,是需要Springboot进行扫描注册的
public interface BookDaomapper {

    //根据ID查询
    @Select("select * from t_comment where id=#{id}")
    public Comment SelectComment(Integer e);

    //增加一条记录
    @Insert("insert into t_comment values(#{id},#{content},#{author},#{aId})")
    public int InsertComment(Comment com);

    //修改一条记录
    @Update("update t_comment set content=#{content} where id=#{id}")
    public int UpdateComment(Comment com);

    //删除一条记录
    @Delete("Delete  from t_comment where id=#{id}")
    public  int DeleteComment(Integer e);
}
  1. 通过测试类检测整合是否成功
 @Autowired
    private BookDaomapper bookDaomapper;
    @Test
    public  void test1(){//查询
   Comment comment=bookDaomapper.SelectComment(1);
        System.out.println(comment);
    }

结果:
在这里插入图片描述

这里发现一个问题,我们的aId为null——这是因为我们的实体类采用的是驼峰命名,这与数据库中的a_id无法对应上。

解决这个问题的办法就是:在Springboot配置文件中添加开启Mybatis识别驼峰命名映射的配置。

mybatis:
  configuration:
      map-underscore-to-camel-case: true   #开启mybatis的驼峰命名映射

重新测试,会发现Springboot成功用注解的方式整合了Mybatis框架
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SpringBoot是一个用于简化Spring应用程序开发的框架。它并没有官方实现Mybatis的启动器,但是Mybatis官方自己实现了一个启动器,可以在pom.xml文件中引入依赖来使用。\[1\]为了开发web工程,需要在pom.xml中引入spring-boot-starter-web依赖,这个依赖包含了Spring WebMVC和Tomcat等web开发的特性。\[2\]在使用SpringBoot快速入门时,需要进行以下步骤:添加依赖spring-boot-starter-web和spring-boot-starter-parent,创建控制器Controller和DispatcherServlet前端控制器,然后启动SpringBoot项目。\[3\]在控制器类上使用注解来标识该类是一个业务控制器,比如使用@SpringBootApplication注解来标识启动类,@Controller注解来标识控制器类。\[3\]至于整合SpringBootSpringMVC和Mybatis框架,可以通过配置文件和注解来实现。具体的整合方式可以根据项目需求和实际情况进行选择和配置。 #### 引用[.reference_title] - *1* *3* [springboot整合mybatis框架](https://blog.csdn.net/qq_42652006/article/details/126833620)[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^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springboot整合mybatisspringmvc](https://blog.csdn.net/sunhongbing1024/article/details/83186783)[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^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨某人的快乐学习日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值