Spring Boot学习笔记(九)


思维导图
开发过程中经涉及到对数据库中的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问、操作都提供了非常好的整合支持。

Spring Boot数据访问概述

Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxx Template以及统一的Repository接口,从而达到简化数据访问层的操作。
SpringData提供多种类型的数据库支持,Spring Boot对SpringData支持的数据库进行整合管理,提供了各种各样的依赖启动器。
在这里插入图片描述

基础环境搭建

MyBatis是持久层框架,它支持定制化SQL、存储过程以及高级映射,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。Spring Boot官方虽然没有对MyBatis进行整合,但是MyBatis团队自行适配了对应的启动器。进一步简化了MyBatis对数据的操作。
搭建步骤

  1. 数据准备:创建数据库、数据表并插入一定的数据

使用的MySQL是5.7版本

创建数据库springbootdata:

CREATE DATABASE springbootdata;

创建数据表t_article

CREATE TABLE t_article(
id int(20) primary key NOT NULL AUTO_INCREMENT COMMENT '文章id',
title varchar(200) DEFAULT NULL COMMENT '文章标题',
content longtext COMMENT '文章内容'
)ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

向数据表t_article插入相关数据

INSERT INTO t_article VALUES('1','Spring Boot基础入门','从入门到精通讲解...');
INSERT INTO t_article VALUES('2','Spring Cloud基础入门','从入门到精通讲解...');

创建数据表t_comment

CREATE TABLE t_comment(
id int(20) PRIMARY KEY NOT NULL AUTO_INCREMENT COMMENT '评论id',
content longtext COMMENT '评论内容',
author varchar(200) DEFAULT NULL COMMENT '评论作者',
a_id int(20) DEFAULT NULL COMMENT '关联的文章id'
)ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

向数据表t_comment插入相关数据

INSERT INTO t_comment VALUES('1','很全、很详细','用户123','1');
INSERT INTO t_comment VALUES('2','感谢分享','用户234','1');
INSERT INTO t_comment VALUES('3','赞一个','用户345','1');
INSERT INTO t_comment VALUES('4','很不错','用户456','1');
INSERT INTO t_comment VALUES('5','很详细','用户567','2');
  1. 创建项目,引入相应的启动器:使用Spring Initializr的方式构建项目,选择MySQL和MyBatis依赖,编写实体类。

添加相关依赖:
在这里插入图片描述
编写实体类Comment
在项目包下创建一个comment对象

public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;//省略getter()/setter()和toString()方法

在项目包下创建一个Article对象

public class Article {
    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;
    //省略getter()/setter()和toString()方法
}
  1. 编写配置文件:在配置文件中进行数据库连接配置以及进行第三方数据源的默认参数覆盖。
  • 在全局配置文件中进行数据库连接配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123

*mysql.jdbc红色报错的话,在pom.xml文件中找到

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

runtime那一行删除即可

  • 设置数据源类型配置(以阿里巴巴的Druid数据源为例)
    在pom.xml文件中插入这段代码:(需要进行下载)
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

如果在开发过程中,需要对这些第三方Druid的运行参数进行重新设置,必须在application.properties配置文件中进行默认参数覆盖
在配置文件中添加如下代码:

#对数据源默认值进行了修改
#数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化连接数
spring.datasource.initalSize=20
#最小空闲数
spring.datasource.minIdle=10
#最大连接数
spring.datasource.maxActive=100

使用注解方式整合MyBatis

整合步骤

  1. 创建Mapper接口文件:@Mapper
    在项目下创建一个mapper包,并创建一个接口文件CommentMapper,编写方法
package com.itheima.chapter03.mapper;

import com.itheima.chapter03.domain.Comment;
import org.apache.ibatis.annotations.*;

@Mapper //表示该类是一个MyBatis接口文件,是需要被Springboot进行扫描的
public interface CommentMapper {

    //查询方法
    @Select("select * from t_comment where id = #{id}")
    public Comment findById(Integer id);

    //添加方法
    @Insert("insert into t_comment values(#{id},#{content},#{author},#{aId}")
    public void insertComment(Comment comment);

    //修改方法
    @Update("update t_comment set content=#{content} where id=#{id}")
    public void updateComent(Comment comment);

    //删除方法
    @Delete("delete from t_comment where id=#{id}")
    public void deleteComment(Integer id);
}

  1. 编写测试方法进行接口方法测试及整合测试
package com.itheima.chapter03;

import com.itheima.chapter03.domain.Comment;
import com.itheima.chapter03.mapper.CommentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Chapter03ApplicationTests {
    @Autowired
    private CommentMapper commentMapper;

    @Test
    void contextLoads() {
        Comment comment = commentMapper.findById(1);
        System.out.println(comment);
    }

}

得到输出结果:
在这里插入图片描述
但是aId的值为null,根据之前插入的相关数据,在命名上有一些不同,数据库中是a_id,可以在application.properties添加如下代码:

#开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true

再次进行测试:
在这里插入图片描述

使用配置文件方式整合MyBatis

整合步骤

  1. 创建Mapper接口文件:@Mapper
    在mapper包下创建一个ArticleMapper接口:
package com.itheima.chapter03.mapper;
import com.itheima.chapter03.domain.Article;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface ArticleMapper {

    //根据id查询文章(包含对应的评论)
    public Article selectArticle();
}

  1. 创建XML映射文件:编写对应的SQL语句
    为了方便管理,在resource下,创建一个Directory命名为mapper,在该mapper下创建一个xml文件命名为:ArticleMappe.xml
<?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.chapter03.mapper.ArticleMapper">
    <select id="selecArticle">
        
    </select>
</mapper>

在select编写前,先在MySQL中执行:

SELECT a.*,c.id c_id,c.content,c.author,c.a_id FROM t_article a,t_comment c WHERE c.a_id= a_id

得到:
在这里插入图片描述

将SQL语句直接粘贴到SELECT语句中,并完善XML文件:

<?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.chapter03.mapper.ArticleMapper">
    <resultMap id="ac" type="Article">
        <id property="id" column="id"></id>
        <result property="title" column="title"></result>
        <result property="content" column="content"></result>
        <collection property="commentList" ofType="com.itheima.chapter03.domain.Comment">
            <id property="id" column="c_id"></id>
            <result property="content" column="content"></result>
            <result property="author" column="author"></result>
            <result property="aId" column="aID"></result>
        </collection>
    </resultMap>
    <select id="selectArticle" resultMap="ac" parameterType="int">
        SELECT a.*,c.id c_id,c.content,c.author,c.a_id FROM t_article a,t_comment c WHERE c.a_id= a.id and a.id=#{aid}
    </select>
</mapper>
  1. 在全局文件中配置XML映射文件路径以及实体类别名映射路径
    在全局配置文件application.properties中,输入以下代码:
#配置MyBatis的xml配置文件路径
mybatis.mapper-locations=classpath:mapper/ArticleMapper.xml

#配置xml映射文件中指定的实体类别名路径
mybatis.type-aliases-package=com.itheima.chapter03.domain
  1. 编写测试方法进行接口方法测试及整合测试
    回到测试类中,编写测试方法:
    @Autowired
    private ArticleMapper articleMapper;
    @Test
    void contextLoads2() {
        Article article = articleMapper.selectArticle(2);
        System.out.println(article);
    }

修改ArticleMapper接口参数值:

package com.itheima.chapter03.mapper;
import com.itheima.chapter03.domain.Article;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface ArticleMapper {

    //根据id查询文章(包含对应的评论)
    public Article selectArticle(Integer id);
}

得到结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值