温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Spring Boot如何对Mybatis进行整合

发布时间:2020-11-26 15:14:00 来源:亿速云 阅读:119 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关使用Spring Boot如何对Mybatis进行整合,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

依赖配置

结合前面的内容,这里我们要嵌入数据库的操作,这里以操作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,其中表结构如下:

使用Spring Boot如何对Mybatis进行整合

接下来就需要来具体的初始化MyBatis配置以及数据表的操作了,先看一下工程结构

使用Spring Boot如何对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

这样即可看到结果

使用Spring Boot如何对Mybatis进行整合 

看完上述内容,你们对使用Spring Boot如何对Mybatis进行整合有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI