Spring Boot整合MyBatis

发布于:2025-03-27 ⋅ 阅读:(112) ⋅ 点赞:(0)

准备工作

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,重写hashcode和equals方法

}
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中添加第三方数据源配置

如果使用mysql,就用下面的配置

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

如果使用h2,就用下面的配置 

spring.datasource.druid.driver-class-name=org.h2.Driver
spring.datasource.druid.url=jdbc:h2:mem:springbootdata
spring.datasource.druid.username=sa
spring.datasource.druid.password=
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());

}

4、控制台显示SQL语句

配置:logging.level.你的Mapper接口文件所在的包名=日志等级

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

使用注解方式访问数据

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.编写测试方法进行整合测试

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

@Test
    public void testFindById(){
       Comment actualComment = commentMapper.findById(1);
       System.out.println(actualComment);
       Comment expectedComment = new Comment(1, "很全、很详细", "狂奔的蜗牛", 1);
       Assert.isTrue(expectedComment.equals(actualComment),"实际输出的评论不是我们想要的评论");

   }

评论关联文章的id没有查询出来,如下图

原因:实体类属性叫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方式访问数据,实现在数据库中增加文章和删除文章功能


网站公告

今日签到

点亮在社区的每一天
去签到