小呆呆的生活

  • 首页
  • 分类
    • Linux
    • MySQL
    • SpringBoot
    • SpringCloud
  • 工具
  • 留言
  • 登录
  • 注册
  • 友情链接
    • 咸鱼的窝
    • DIY熙的家
    • Farmer的自习室
    • Dark的小黑屋
  • 关于
人的一生注定会遇到两个人
一个惊艳了时光,一个温柔了岁月
  1. 首页
  2. SpringBoot框架
  3. 正文

Spring Boot整合MyBatis

2020年 4月 12日 793次阅读 0人点赞 0条评论

基础环境搭建:

搭建步骤:

  1. 数据准备:创建数据库、数据表并插入一定的数据。
  2. 创建项目,引入相应的启动器:使用Spring Initializr的方式构建项目,选择MySQL和MyBatis依赖,编写实体类。
  3. 编写配置文件:在配置文件中进行数据库连接配置以及进行第三方数据源的默认参数覆盖。
  • 创建数据库:
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');
  • 引入依赖(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>
  • 创建实体类:
public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;
}
  • 编写配置文件(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);}
    }
    

     

  2. 编写测试方法进行接口方法测试及整合测试

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MyBatisDemoApplicationTests {
        @Autowired
        private CommentMapper commentMapper;
        @Test
        public void selectComment() {
            Comment comment = commentMapper.findById(1);
            System.out.println(comment);
        }
    }
    

使用配置文件整合MyBatis:

整合步骤:

  1. 创建Mapper接口文件:@Mapper

    @Mapper
    public interface ArticleMapper {
        public Article selectArticle(Integer id);
        public int updateArticle(Article article);
    }
    
  2. 创建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>
    

     

  3. 在全局文件(application.properties)中配置XML映射文件路径以及实体类别名映射路径

    #配置MyBatis的xml配置文件路径
    mybatis.mapper-locations=classpath:mapper/*.xml
    #配置XML映射文件中指定的实体类别名路径
    mybatis.type-aliases-package=com.xiaodaidai.domain
    
  4. 编写测试方法进行接口方法测试及整合测试

    @Autowired
    private ArticleMapper articleMapper;
    @Test
    public void selectArticle() {
        Article article = articleMapper.selectArticle(1);
        System.out.println(article);
    }
    
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: Java Mybatis SpringBoot
最后更新:2021年 7月 13日

小呆呆

知足常乐,就会拥有幸福

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

小呆呆

知足常乐,就会拥有幸福

最新 热点 随机
最新 热点 随机
数据库索引简析 Java多线程的使用场景以及线程的创建方式 Spring事务的使用示例和传播行为以及失效场景 Spring Boot使用JUnit和Mockito进行Service层单元测试 Spring Cloud Zuul和Gateway的简单示例(搭建方式) Spring Cloud的网关Zuul和Gateway
Java面试高频(五) Reids客户端Jedis的访问模式(下) 解决Spring Initializr只能创建为Java 17版本以上的问题 grep 'temporary password' /var/log/mysqld.log打印为空 Spring Boot使用JUnit和Mockito进行Service层单元测试 Java面试高频(四)
标签聚合
SpringCloud SpringBoot 面试 MySQL Spring 后端 干货 Java
最近评论
我是可是尼古拉斯·爱新觉·罗·G·钰豪啊 发布于 3 年前(04月08日) 我来注水了胜哥 :hehe:
鸟人金 发布于 3 年前(03月03日) v
鸟人金 发布于 3 年前(03月03日) 胜哥yyds
鸟人金 发布于 3 年前(03月03日) 我滴偶像!!!!!!!!!!!!!!!
水军2号 发布于 3 年前(03月03日) 胜哥tql
归档
  • 2024 年 2 月
  • 2024 年 1 月
  • 2023 年 12 月
  • 2023 年 11 月
  • 2023 年 10 月
  • 2023 年 8 月
  • 2023 年 6 月
  • 2022 年 11 月
  • 2022 年 8 月
  • 2022 年 6 月
  • 2022 年 4 月
  • 2022 年 3 月
  • 2022 年 1 月
  • 2021 年 12 月
  • 2021 年 9 月
  • 2021 年 8 月
  • 2021 年 6 月
  • 2021 年 4 月
  • 2020 年 10 月
  • 2020 年 9 月
  • 2020 年 8 月
  • 2020 年 7 月
  • 2020 年 6 月
  • 2020 年 5 月
  • 2020 年 4 月
  • 2020 年 3 月

COPYRIGHT © 2023 小呆呆的生活. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备2020104583号

粤公网安备44011802000463号