当前位置: 首页 > 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,重写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;@Testpublic 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 mapperPUBLIC "-//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.authorFROM t_article a,t_comment cWHERE 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方式访问数据,实现在数据库中增加文章和删除文章功能


http://www.mrgr.cn/news/95668.html

相关文章:

  • Python个人学习笔记(19):模块(正则表达式)
  • 【MySQL】内置函数
  • Linux安装Ollama+MaxKB建立本地知识库
  • 全息教学系统的软件开发,沉浸式数字沙盘展示系统如何改变历史教学
  • LangChain组件Tools/Toolkits详解(6)——特殊类型注解Annotations
  • 风控笔记4——市场风险管理
  • (UI自动化测试web端)第二篇:元素定位的方法_class定位
  • DigitalFoto公司如何用日事清流程管理工具实现任务优先级与状态可视化?
  • Jackson的核心类与API方法:ObjectMapper、JsonNode、ObjectNode、ArrayNode
  • Blender导出fbx到Unity找不到贴图的问题
  • C++面试题总结
  • 【NLP 42、实践 ⑪ 用Bert模型结构实现自回归语言模型的训练】
  • (UI自动化测试web端)第二篇:元素定位的方法_xpath路径定位
  • Maven下载以及项目创建(笔记)
  • CSS动画
  • 51c自动驾驶~合集26
  • Linux系统管理与编程08:任务驱动综合应用
  • 深入理解Java享元模式及其线程安全实践
  • 网络安全学习-博客文序记
  • CentOS系统下安装tesseract-ocr5.x版本