J2EE平台应用与开发(九)Spring Boot数据访问

一、Spring Boot数据访问概述

1、Spring Boot默认采用整合Spring Data的方式统一处理数据访问层

通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。
Spring Data提供了多种类型数据库支持,Spring Boot对Spring Data支持的数据库进行了整合支持,提供了各种依赖启动器。

二、Spring Boot整合MyBatis

1、基础环境搭建

(1)数据准备,创建数据库、数据表并插入一定的数据
(2)创建项目,引入相应的启动器:使用Spring Initializr的方式构建项目,选择MySQL和MyBatis依赖,编写实体类
(3)编写配置文件:在配置文件中进行数据库连接配置以及进行第三方数据源的默认参数覆盖

2、使用注解的方式整合MyBatis

(1)创建Mapper接口文件:

@Mapper//@Mapper注解表示该类是一个MyBatis接口文件,并保证能够被Spring Boot自动扫描到Spring容器中
public interface CommentMapper {
//在接口内部,分别通过@Select、@Insert、@Update、@Delete注解配合SQL语句完成对数据库表的增删改查操作
    //插入评论数据
    @Insert("INSERT INTO t_comment(content,author,a_id)"+"values (#{content},#{author},#{aid})")
    int insertComment(Comment comment);

    //删除
    @Delete("DELETE FROM t_comment WHERE id=#{id}")
    int deleteComment(Integer id);

    //查询
    @Select("SELECT * FROM t_comment WHERE id =#{id}")
    Comment findById(Integer id);

    //更新
    @Update("UPDATE t_comment SET content=#{content} WHERER id=#{id}")
    int updateComment(Comment comment);
}

(2)编写单元测试进行接口方法测试

@SpringBootTest//标记单元测试类,并加载项目上下文环境
class DemoApplicationTests {
    @Autowired//将CommentMapper接口自动装配为Spring容器中的Bean
    private CommentMapper commentMapper;

    @Test//标注findCommentByIdTest()是单元测试方法
    void findCommentByIdTest() {
        Comment comment=commentMapper.findById(1);
        System.out.println(comment.toString());
    }
}

(3)整合测试

3、使用配置文件的方式整合MyBatis

(1)创建Mapper接口文件
(2)创建XML映射文件(ArticleMapper.xml)

<mapper namespace="com.example.lesson10.mapper.ArticleMapper">//<mapper>标签的namespace属性值对应的是ArticleMapper接口文件的全路径名称

(3)配置XML映射文件路径(application.properties)

(4)编写单元测试进行接口方法测试
(5)整合测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值