Spring Boot+Mybatis的整合过程
作者:hello_hjz 发布时间:2023-12-20 06:50:18
依赖配置
结合前面的内容,这里我们要嵌入数据库的操作,这里以操作MySQL为例整合Mybatis,首先需要在原来的基础上添加以下依赖
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
当然啦,只依赖mybatis是不够的还需要依赖jdbc驱动以及返回json数据的json库(格式化数据)
<!-- MySql驱动 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!--Json库的依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.43</version>
</dependency>
应用配置
接着需要在application.properties中添加数据库配置
#JDBC配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/weibo?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
这里连接的数据库名叫weibo,其中表结构如下:
接下来就需要来具体的初始化MyBatis配置以及数据表的操作了,先看一下工程结构
编写配置类
数据库相关的DataSource,SqlSeesion配置,其中DataSourse的配置可以理解为解读application.properties中的jdbc相关配置然后初始化JDBC驱动的,SqlSeesion配置主要是针对Mybatis使用事务操作时的配置信息。
package com.example.demo.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
@EnableAutoConfiguration
@ComponentScan
@MapperScan("com.example.demo.mapper")
public class JdbcConfig {
// DataSource配置
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
// 提供SqlSeesion(数据库事务操作相关的配置)
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
添加Pojo类
该类主要接收数据表中的数据,所以属性基本上跟数据表的属性一致
package com.example.demo.bean;
public class Diary {
private int id;
private String title;
private String content;
private String pubTime;
private int userId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPubTime() {
return pubTime;
}
public void setPubTime(String pubTime) {
this.pubTime = pubTime;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "Diary [id=" + id + ", title=" + title + ", content=" + content + ", pubTime=" + pubTime + ", userId="
+ userId + "]";
}
}
添加数据表操作接口
该类描述了操作数据表的过程,SprintBoot在运行中会根据类上的@Mapper注解找到它,因此不能落下这个注解
package com.example.demo.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.example.demo.bean.Diary;
@Mapper
public interface DiaryMapper {
@Select("select * from diary where _id = #{id}")
public Diary getDiaryById(@Param("id")Integer id);
}
使用
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.example.demo.bean.Diary;
import com.example.demo.mapper.DiaryMapper;
@RestController
public class DiaryMappingController {
@Autowired
DiaryMapper diaryMapper;
@RequestMapping("/diary")
public String getDiary(Integer id){
Diary d = diaryMapper.getDiaryById(id);
String json = JSON.toJSONString(d);
return json;
}
}
最后运行SpringBoot项目,然后在浏览器上输入网址:
http://localhost:8080/diary?id=2
这样即可看到结果
到此SpringBoot+Mybatis的整合就完成了
源码:https://github.com/huajianzh/spring/tree/master/springdemo
以上所述是小编给大家介绍的Spring Boot+Mybatis的整合过程网站的支持!
来源:http://blog.csdn.net/new_huiyuan/article/details/74627432


猜你喜欢
- 一、线程同步概述前面的文章都是讲创建多线程来实现让我们能够更好的响应应用程序,然而当我们创建了多个线程时,就存在多个线程同时访问一个共享的资
- 前言AOP(Aspect Oriented Programming),即面向切面编程,是Spring框架的大杀器之一。首先,我声明下,我不是
- 已经有很多关于 Flutter WebView 的文章了,为什么还要写一篇。两个原因:Flutter WebView 是 Flutter 开
- 本文实例讲述了Android自定义照相机Camera出现黑屏的解决方法。分享给大家供大家参考,具体如下:对于一些手机,像HTC,当自定义Ca
- 本文介绍了Spring Boot 与DBunit 配合使用方法,分享给大家,具体如下:DBUnit快速上手Springboot 添加 DBu
- 配置Servlet的方法有俩种,分别是传统web.xml文档中部署servlet和注解方式部署servlet,下面就先一起来学习 * 解方式部
- 前言小伙伴们在使用C#开发时,可能需要将一些信息写入到txt,这里就给大家介绍几种常用的方法。方法:1.将由字符串组成的数组写入txt此种方
- 在android中做图像镜像有很多方法,今天算是学习了! 两种方法如下: //方法一 Matrix matrix = new Matrix(
- 一、首先在Application的onCreate中写:// GeneralAppliction.javapublic static IWX
- 前言最常用的对字符串操作的类有三个,分别是String,StringBuilder,StringBuffer,下面将会详细的说说这三个类..
- 1. 常规使用请求一个权限,然后接收结果回调HoloPermission.with(this,Manifest.permission.WRI
- java POI合并两个word文档有需要的可以将主函数中写死的地方改为一个Listimport java.io.FileInputStre
- 创建我们来看看,使用Arrays 怎么创建一个新的数组,一般来说,我们可以使用Arrays 的 copyOf , copyOfRange 和
- 最大单词长度乘积给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]
- 为了实现自定义的Menu和ContextMenu效果,下面演示代码通过派生ProfessionalColorTable类,在自定义的类中重写
- 使用spring redis的increment方法时,报错:nested exception is redis.clients.jedis
- 我就废话不多说啦,大家还是直接看代码吧~[ { "orderNo": "3213123123123
- 简介Arthas 是Alibaba开源的Java诊断工具,动态跟踪Java代码;实时监控JVM状态,可以在不中断程序执行的情况下轻松完成JV
- 我们在日常开发中,经常会遇到类似的场景:当要做一件事儿的时候,这件事儿的步骤是固定好的,但是每一个步骤的具体实现方式是不一定的。通常,遇到这
- 前言此节假日为严格按照国家要求的双休和法定节假日并且包含节假日的补班信息,大家可根据自己的需求自定义处理哦。以下为Maven配置,是程序用到