IDEA-Spring Boot整合mybatis

	Spring Data是Spring提供的一个用于简化数据库访问、支持云服务的开源框架。
	Spring Boot默认采用整合Spring Data的方式统一处理数据访问层,通过添加大量自动配置,
引入各种数据访问模板xxxTemplate以及统一的Repository接口,达到简化数据访问层的操作。

整合Mybatis

	SpringData提供了多种类型数据库支持,Spring Boot对Spring Data支持的数据库进行了整合
管理,提供了各种依赖启动器,如jpa、mongoDB、neo4j、redis。
	SpringBoot没有提供Mybatis场景依赖,其开发团队自己适配了mybatis-spring-boot-starter依赖
启动器实现数据访问操作。
  • Mybatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。

环境搭建

  • 数据库准备

 create table 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;
 // INNODB:指定mysql引擎 
 // AUTO_INCREMENT=2:指定自增从2开始
 // 设置表编码:utf8
 
insert into article values(1,'Spring boot base','from base to hard');
insert into article values(2,'Spring data base','from base to hard');

 create table comment(
    id int(20) not null auto_increment comment '评论id',
    content longtext comment '评论内容',
    author varchar(200) default null comment '评论作者',
    articleId int (20) default null comment '关联文章id',
    primary key(id)
    )ENGINE=INNODB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
insert into comment values(1,'赞','张三',1);
insert into comment values(2,'赞赞','李四',1);
insert into comment values(3,'赞赞赞','王五',1);
insert into comment values(4,'赞赞赞赞','王朝',1);
insert into comment values(5,'赞赞赞赞赞','马汉',2);
  • 创建项目
    • 新建SpringBoot项目,添加模块web,Mybatis(提供mybatis框架来操作数据库)和MySQL driver(提供MySQL数据库连接驱动)
  • 编写对应实体类
public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer articleId;
	...省略toString set get
}
public class Article {
    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;
    ...省略toString set get
}
  • 添加Druid数据源依赖
<!--    配置数据源类型 阿里巴巴Druid数据源    -->
<!--   SpringBoot会自动识别配置Druid数据源   -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.1</version>
        </dependency>
  • 数据库连接配置
# MySQL数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/springdata?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin

# 添加并配置第三方数据源Druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 由于Spring Boot提供的数据源自动配置类中没有这些参数对应的默认属性,无法识别
# 下面三个配置需要编写自定义配置类,将属性注入到Druid数据源属性中
spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=20

  • 编写自定义配置类进行Druid属性注入
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDruid(){
        return new DruidDataSource();
    }
}

使用注解的方式整合Mybatis

  • 创建Mapper接口文件
    • Mapper注解:表示该类是一个Mybatis接口文件,并保证能够被SpringBoot自动扫描到Spring容器中
    • 接口内部,分别通过@Select、@Insert、@Update、@Delete注解配合SQL语句完成增删改查操作
    • @MapperScan(“com.example.mapper”):表示扫描该文件夹下Mapper接口,该注解添加到项目启动类上。

@Mapper
public interface CommentMapper {

    @Select("select * from comment where id=#{id}")
    public Comment findById(Integer id);

    @Insert("insert into comment(content,author,articleId) values (#{content},#{author},#{articleId})")
    public int insertComment(Comment comment);

    @Update("update comment set content=#{content} where id=#{id}")
    public int updateComment(Comment comment);

    @Delete("delete from comment where id=#{id}")
    public int deleteComment(Integer id);
}

  • 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest
class Chapter03ApplicationTests {

    @Autowired
    private CommentMapper commentMapper;
    @Test
    void contextLoads() {
    }

    @Test
    public void selectComment(){
        Comment comment = commentMapper.findById(5);
        System.out.println(comment);
    }
}

  • 运行结果

在这里插入图片描述

  • 注意:如果在实体类中使用了驼峰命名法命名属性,需要再全局配置文件中加入
# 开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true

使用配置文件的方式整合Mybatis

  • 创建接口文件
@Mapper
public interface ArticleMapper {
    public Article selectArticle(Integer id);
    public int updateArticle(Article article);
}
  • 创建XML映射文件
    • 关于具体Mybatis映射文件中SQL语句的具体用法,查看官方文档
    • 注意XML定义表头 该XML为mapper映射文件,而非config配置文件
<?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.example.chapter03.mapper.ArticleMapper">
    <!--    查询文章详细(包括评论信息)-->
    <select id="selectArticle" resultMap="articleWithComment">
        select a.*, c.id c_id, c.content c_content, c.author ,c.articleId
        from article a, comment c
        where a.id=c.articleId and a.id=#{id}
    </select>
    <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"/>
            <result property="articleId" column="articleId"/>
        </collection>
    </resultMap>
    <!--    根据文章id更新文章信息-->
    <update id="updateArticle" parameterType="Article">
        update 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>
  • 配置XML映射文件路径 在全局配置文件中
#配置Mybatis的XML配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置XML映射文件中指定的实体类别名路径
mybatis.type-aliases-package=com.example.chapter03.domain
  • 编写测试类测试(更新操作仅需传入一个article对象更新即可)
    @Autowired
    private ArticleMapper articleMapper;
    @Test
    public void selectArticle(){
        Article article = articleMapper.selectArticle(1);
        System.out.println(article);
    }
}
  • 测试结果

在这里插入图片描述

ps: 还需要熟悉xml映射文件中的语法规则
  • 对比

    • 注解方式适合增删改查操作
    • 配置文件方式相对麻烦,但是对于复杂数据操作比较实用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值