SpringBoot整合MyBatis的简单介绍

4 篇文章 0 订阅
3 篇文章 0 订阅


前言

\qquad SpringBoot项目往往会整合MyBatis一起使用,这里简单教一下大家搭建的步骤。


一、搭建步骤

  1. 数据准备:创建数据库、数据表并插入一定的数据。
  2. 创建项目,引入相应的启动器:使用Spring Initializr的方式构建项目,选择MySQLMyBatis依赖,编写实体类。
  3. 编写配置文件:在配置文件中进行数据库连接配置以及进行第三方数据源的默认参数覆盖。

1、创建数据库

CREATE DATABASE springbootdata;
CREATE TABLE `t_article` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
  `title` varchar(200) NULL COMMENT '文章标题',
  `content` longtext COMDEFAULTMENT '文章内容',
  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基础入门', '从入门到精通讲解...');
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、引入依赖(pom.xml)

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

3、创建实体类:

public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;
}

4、编写配置文件(application.properties)

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=用户名
spring.datasource.password=密码
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100

二、整合MyBatis

1、使用注解方式

  • 创建Mapper接口文件:@Mapper
@Mapper
public interface CommentMapper {
	//查询数据操作
	@Select("SELECT * FROM t_comment WHERE id =#{id}")
	public Comment findById(Integer id);
	//插入数据操作
	@Insert("INSERT INTO t_comment(content,author,a_id) " +
            "values (#{content},#{author},#{aId})")
	public int insertComment(Comment comment);
	//更新数据操作
	@Update("UPDATE t_comment SET content=#{content} WHERE id=#{id}")
	public int updateComment(Comment comment);
	//删除数据操作
	@Delete("DELETE FROM t_comment WHERE id=#{id}")
	public int deleteComment(Integer id);}
}
  • 编写测试方法进行接口方法测试及整合测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBatisDemoApplicationTests {
	@Autowired
	private CommentMapper commentMapper;
	@Test
	public void selectComment() {
		Comment comment = commentMapper.findById(1);
		System.out.println(comment);
	}
}

2、使用配置文件方式

  • 创建Mapper接口文件:@Mapper
@Mapper
public interface ArticleMapper {
    public Article selectArticle(Integer id);
    public int updateArticle(Article article);
}
  • 创建XML映射文件:编写对应的SQL语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xiaodaidai.mapper.ArticleMapper">
    <resultMap id="articleWithComment" type="Article">
        <id property="id" column="id" />
        <result property="title" column="title" />
        <result property="content" column="content" />
        <collection property="commentList" ofType="Comment">
            <id property="id" column="c_id" />
            <result property="content" column="c_content" />
            <result property="author" column="author" />
        </collection>
    </resultMap>
    <select id="selectArticle" resultMap="articleWithComment">
       SELECT a.*,c.id c_id,c.content c_content,c.author
       FROM t_article a,t_comment c
       WHERE a.id=c.a_id AND a.id = #{id}
    </select>
	<update id="updateArticle" parameterType="Article" >
        UPDATE t_article
        <set>
            <if test="title !=null and title !=''">
                title=#{title},
            </if>
            <if test="content !=null and content !=''">
                content=#{content}
            </if>
        </set>
        WHERE id=#{id}
    </update>
</mapper>
  • 在全局文件(application.properties)中配置XML映射文件路径以及实体类别名映射路径
#配置MyBatis的xml配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置XML映射文件中指定的实体类别名路径
mybatis.type-aliases-package=com.xiaodaidai.domain
  • 编写测试方法进行接口方法测试及整合测试
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle() {
	Article article = articleMapper.selectArticle(1);
	System.out.println(article);
}

总结

  • 本文简单为大家介绍了SpringBoot整合MyBatis的方式,推荐使用注解方式比较方便。
  • 欢迎大家提出建议以及批评,有任何问题可以私信。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xiaodaidai丶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值