当前位置: 首页 > news >正文

Spring Boot整合MyBatis

准备工作

1、创建SpringBoot项目,以及在pom.xml中添加如下依赖

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.2</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

2、新建domain子包,然后再新建两个实体类(CommentArticle)

public class Comment {

    private Integer id;
    private String content;
    private String author;
    private Integer aId;

//添加set 、get、 toString

}
public class Article {

    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;

    //添加set 、get、 toString

}

3、整合Druid:

导入Druid对应的starter:

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

在application.properties中添加数据库连接配置和第三方数据源配置

spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.initialSize=20
spring.datasource.druid.minIdle=10
spring.datasource.druid.maxActive=100

测试是否整合成功

@Autowired
private DruidDataSource dataSource;

@Test
public void testDruidDataSource() {

    System.out.println(dataSource.getMaxActive());

}

使用注解方式访问数据

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);

}

提示:如果接口文件过多,可以在启动类上添加@MapperScan(“接口文件所在的包名”),不必再接口文件上添加@Mapper.

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

控制台显示SQL:

logging.level.你的Mapper包=日志等级

例如:logging.level.com.itheima.myblog.mapper=debug

@Autowired
//会报错,但不影响执行,可以在Mapper接口中添加//@Component(“commentMapper”)
private CommentMapper commentMapper;

@Test
public void selectComment() {

    Comment comment = commentMapper.findById(1);
    System.out.println(comment);

}

关联对象没有查询出来,如下图

原因:实体类叫aId,数据表叫a_id,名称不一致,导致映射不成功。

解决方法:因为aId按驼峰命名的,所以开启驼峰命名匹配映射

mybatis.configuration.map-underscore-to-camel-case=true

使用配置文件方式访问数据

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

@Mapper
public interface ArticleMapper {

    public Article selectArticle(Integer id);

    public int updateArticle(Article article);


}

2.创建XML映射文件:编写对应的SQL语句

创建文件夹mapper,不是资源文件夹,如下图

<?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.itheima.mapper.ArticleMapper">

    <!-- 1、查询文章详细(包括评论信息) -->
    <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>

    <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>

    <!-- 2、根据文章id更新文章信息 -->
    <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.在全局文件中配置XML映射文件路径以及实体类别名映射路径

#配置MyBatisxml配置文件路径

mybatis.mapper-locations=classpath:mapper/*.xml

#设置XML映射文件中的实体类别名的路径

mybatis.type-aliases-package=com.itheima.domain

4.编写测试方法进行整合测试

@Autowired
private ArticleMapper articleMapper;

@Test
public void selectArticle() {

    Article article = articleMapper.selectArticle(1);

    System.out.println(article);

}

动手试一试

使用XML方式访问数据,实现在数据库中增加文章和删除文章功能

相关文章:

  • 智能搜索时代:如何通过AI搜索与GEO策略打造品牌护城
  • 银河麒麟操作系统的上下游版本判断
  • AI鸟类识别技术革新生态监测:快瞳科技如何用“智慧之眼”守护自然?
  • yarn 装包时 package里包含sqlite3@5.0.2报错
  • ruoyi-vue部署4
  • 第六届电气、电子信息与通信工程国际学术会议 (EEICE 2025)
  • Hadoop NN和JN VERSION版本不一致
  • 洛谷题目:P1018 [NOIP 2000 提高组] 乘积最大 题解
  • day16 没进展怎么炼丹
  • C++之继承与多态(含模版进阶)
  • FRP内网穿透的原理与基础配置指南
  • Windows 事件日志中登录类型(Logon Type)
  • 本地JAR批量传私服
  • 基于 Prompt 的实体关系抽取:原理与优势解析
  • Python:文件的基本操作与基本读写
  • 访问者模式
  • 【动态规划】详解多重背包问题
  • Java求101-200之间有多少素数
  • 西门子200smart之modbus_TCP(做主站与第三方设备)通讯
  • Siddon 算法学习中的疑问
  • 人民日报评论员:把造福人民作为根本价值取向
  • 巴菲特股东大会前瞻:执掌伯克希尔60年,巨轮将驶向何方
  • 受天气等影响SC8041航班三次备降延误超12小时,山航致歉
  • 空间站第八批科学实验样品返抵地球并交付科学家
  • 居委业委居民群策群力,7位一级演员来到上海一小区唱戏
  • 耶路撒冷发生山火,以防长宣布紧急状态